Tuesday, May 17, 2011

Catching Multiple Exception Types with One Handler in java

Consider the following code here, which has to deal with 2 exceptions. Now to handle this exception, we have to apply 2 catch blocks to handle the exception which we have shown here.

The two exception handlers used by the writeList method are very specialized. Each handles only one type of exception. The Java language allows you to write general exception handlers that handle multiple types of exceptions.As you know, Java exceptions are Throwable objects; they are instances of Throwable or a subclass of Throwable. The Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes. We have discussed the hierarchy here.

Your exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type. If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses.Let's modify the writeList method once again. Only this time, let's write it so that it handles both IOExceptions andArrayIndexOutOfBoundsExceptions. The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exceptionclass. An exception handler that handles both types of exceptions looks like this:

try {
. . .
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}

The class is pretty high in the Throwable class hierarchy. So in addition to the IOException and ArrayIndexOutOfBoundsExceptiontypes that this exception handler is intended to catch, it will catch numerous other types. Generally speaking, your exception handlers should be more specialized. Handlers that can catch most or all exceptions are typically useless for error recovery because the handler has to determine what type of exception occurred anyway to determine the best recovery strategy. Also, exception handlers that are too general can make code more error prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended.


No comments:

Post a Comment

Chitika