How to use chained exceptions
Description
The chained exception allows you to associate another exception with an exception. This second exception describes the cause of the first exception.
Syntax
To allow chained exceptions, two constructors and two methods were added to Throwable
.
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
Example
Here is an example that illustrates the mechanics of handling chained exceptions:
public class Main {
static void demoproc() {
NullPointerException e = new NullPointerException("top layer");
e.initCause(new ArithmeticException("cause"));
throw e;// w w w. j a va2 s .c om
}
public static void main(String args[]) {
try {
demoproc();
} catch (NullPointerException e) {
System.out.println("Caught: " + e);
System.out.println("Original cause: " + e.getCause());
}
}
}
The code above generates the following result.