Java Reference
In-Depth Information
method raising the exception was called, the style of code in which each call is wrapped in a
try…catch clause may be needed. This is a rare case, but one that does arise.
Our example was simplified because all of the methods that throw an exception throw the
same exception. But this is not required to cluster a group of method calls within a particular
try block. All that is required is that all of the exceptions that can be thrown by any of the
methods called in the try block have a catch clause. It is still possible to separate the mainline
code from the exception-handling code.
The one trick that can cause trouble when catching multiple exception types is making sure
that you don't get crossed up by the type system. When an exception is thrown, the catch
block used as the return point is the first one encountered that deals with exceptions of that
type. But an exception is a Java object, and Java objects can have multiple types; they are not
only the type they are declared to be, but also of the type of any super-types of their declared
type. This means that if there is a catch clause for a super-type of an exception listed prior
to the catch clause for that exception, the second catch clause will never be the return point
when that exception is thrown. Instead, the super-type exception will be caught by the earlier
An example might help here. Suppose we have an exception called Type1Exception and
another exception called Type2Exception , and that Type2Exception extends Type1Excep-
tion . This is the sort of thing that can happen when one exception is a more specific instance
of a more general exception. Now suppose that you have a method (call it method1() ) that
can throw a Type1Exception , and a method (call it method2() ) that can throw a Type2Ex-
ception . If method1() and method2() both occur inside the same try block, it is important
how you order the catch blocks associated with the try block. If your code looks like:
} catch (Type2Exception e){
//do something to recover
} catch (Type1Exception e) {
//do something else to recover
Search WWH ::

Custom Search