Java Reference
In-Depth Information
the results will be as you expect. If a Type2Exception is thrown, the first block of recovery
code will be performed; and if a Type1Exception is thrown, the second block of recovery
code will be used instead. But if your code looks like:
try{
...
method1();
...
method2();
...
} catch (Type1Exception e){
//do something to recover
} catch (Type2Exception e) {
//do something else to recover
}
the second catch block will never be entered. That is because when an exception is thrown,
it is caught by the first exception handler that matches the type of the thrown exception. Since
a Type2Exception is a subclass of a Type1Exception , any Type2Exception will be caught
by the first exception handler.
This sort of problem can be hard to discover when it actually happens. So when you are writ-
ing a block of code that can throw multiple exceptions, you had better take a look at all of the
types (both exact and inherited) of the exceptions being thrown, and make sure that your ex-
ception handlers are declared in the correct order. You can always find such an order, since the
inheritance hierarchy of any set of exceptions will form a tree rooted in the class Exception
(if there were multiple class inheritance, this might not be the case). But you do need to be
careful.
Of course, this advice assumes that the programmer is actually doing her job. With respect to
exceptions, this often is not the case. I have heard it argued that the most common form of
exception handler in Java is:
} catch (Exception e){
//TODO: to be written
}
perhaps with the comment removed. I've not seen this, because I work with adults, but I have
seen far too many exception handlers of the form:
Search WWH ::




Custom Search