Java Reference
In-Depth Information
Rethrowing an Exception
An exception that is caught can be rethrown. You may want to rethrow an exception for different reasons. One of the
reasons could be to take an action after catching it, but before propagating it up the call stack. For example, you may
want to log the details about the exception and then rethrow it to the client. Another reason is to hide the exception
type/location from the client. You are not hiding the exceptional condition itself from the client. Rather, you are hiding
the type of the exceptional condition. You may want to hide the actual exception type from clients for two reasons:
The client may not be ready to handle the exception that is thrown, or
Rethrowing an exception is as simple as using a throw statement. The following code snippet catches the
exception, prints its stack trace, and rethrows the same exception. When the same exception object is rethrown, it
preserves the details of the original exception.
The exception that is thrown does not make sense to the client.
try {
// Code that might throw MyException
}
catch(MyException e) {
e.printStackTrace(); // Print the stack trace
// Rethrow the same exception
throw e;
}
When an exception is thrown from a catch block, another catch block in the same group is not searched to
handle that exception. If you want to handle the exception thrown from a catch block, you need to enclose the code
that throws the exception inside another try-catch block. Another way to handle it is to enclose the whole try-catch
block inside another try - catch block. The following snippet of code shows the two ways of arranging nested try-catch
to handle Exception1 and Exception2 . The actual arrangement of nested try-catch depends on the situation at
hand. If you do not enclose the code that may throw an exception inside a try block or the try block does not have
a matching associated catch block that can catch the exception, the runtime will propagate the exception up the call
stack provided the method is defined with a throws clause.
// #1 - Arranging nested try-catch
try {
// May throw Exception1
}
catch(Exception1 e1) {
// Handle Exception1 here
try {
// May throw Exception2
}
catch(Exception2 e2) {
// Handle Exception2 here
}
}
 
Search WWH ::




Custom Search