Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Can catch blocks be polymorphic?

In a paper I'm going over for a repeat exam, I'm asked "Can catch blocks be polymorphic?".

If true, it doesn't make sense to me to call multiple catch blocks polymorphic. Is it polymorphism if catch blocks cannot be named and only contain parameters in their method header?

For example:

try {

//...

} catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: " + e.getMessage());
    throw new SampleException(e);

} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

In this, are these two catch blocks polymorphic?

like image 419
DagdA Avatar asked Feb 12 '23 05:02

DagdA


1 Answers

The example you posted should be described as overloading. The only thing different from overloading is a readability requirement that subclasses appears before its superclass.

The statement "Polymorphic catch blocks" requires a bit of gymnastics to parse.

After completing said gymnastics I would interpret it as

  • A catch block providing a different implementation depending on the type of object being caught.

Something similar to

try{


} catchwith ( catchHandlerObject );

And catchHandlerObject is polymorphic. I.e. handles the same exception differently depending on the (runtime) type of catchHandlerObject.

Is

class C{
   public void m(Object o){ .... };
}

Is m(Object o) polymorphic? I would say that the consensus is that it is unnecessary to include polymorphism in to this description. A call m( stringObject ). is not indicative of polymorphism.

I go contrary to the previous posters an say no. Polymorphic is not the proper way to label this situation. Polymorphism is not the proper way to describe what is happening.

I also really think you should double check this with your TA or your professor. It happens regularly that questions include mistakes ranging from spelling to completely out of mind experiences.

As yshavit noted, overloading indicates a compile time binding. The catch-block is by necessity resolved at runtime. I'm at a loss finding a better term than overloading though.

like image 59
Captain Giraffe Avatar answered Feb 15 '23 10:02

Captain Giraffe