Java Reference
In-Depth Information
/* #2 - Arranging nested try-catch */
try {
try {
// May throw Exception1
}
catch(Exception1 e1) {
// Handle Exception1 here
// May throw Exception2
}
}
catch(Exception2 e2) {
// Handle Exception2 here
}
The following snippet of code shows how to catch an exception of one type and rethrow an exception of
another type:
try {
// Code that might throw a MyException
}
catch(MyException e) {
e.printStackTrace(); // Print the stack trace
// Rethrow another type of exception
throw new RuntimeException(e.getMessage());
}
The catch block catches the MyException , prints its stack trace, and rethrows a RuntimeException . In the
process, it loses the details of the original exception that was thrown. When the RuntimeException is created, it
packages the information of stack frames from the point where it was created. The client gets the information about
the rethrown RuntimeException from the point it was created, not about the original MyException . In the above code,
you have hidden both the type and the location of the original exception from the client.
You can also rethrow another type of exception and use the original exception as the cause of the rethrown
exception. It is as if the new exception is a wrapper for the original exception. You can set the cause of an exception
using one of the constructors of the new exception type that accepts a cause as a parameter. You can also use the
initCause() method to set the cause of the exception. The following snippet of code rethrows a RuntimeException
setting MyException as its cause:
try {
// Code that might throw a MyException
}
catch(MyException e) {
e.printStackTrace(); // Print the stack trace
// Rethrow a new exception using original exception as its cause
throw new RuntimeException(e.getMessage(), e);
}
You also have the option just to hide the location of the exception from the client when you rethrow an exception.
The fillInStackTrace() method of the Throwable class fills in the stack trace information to an exception object
from the point where this method is called. You need to call this method on the exception you catch and want
 
Search WWH ::




Custom Search