Chaining Exceptions
ApplicationException.java
We can extend Exception to take a second parameter, a reference to the original exception.
When we print a stack trace, we add the original exceptions's stack trace to it:
Running: c:\jdk1.3\bin\java -mx64m TestExceptions
ApplicationException: Oh, no!
at TestExceptions.thisWillFail(TestExceptions.java:19)
at TestExceptions.main(TestExceptions.java:8)
Caused by: java.lang.Exception
at TestExceptions.methodTwo(TestExceptions.java:32)
at TestExceptions.methodOne(TestExceptions.java:27)
at TestExceptions.thisWillFail(TestExceptions.java:16)
at TestExceptions.main(TestExceptions.java:8)
0 error(s)
Exceptions In JDK 1.4
In JDK 1.4 and later, the exception classes have been retrofitted with this new functionality.
See
Chained Exceptions
and
Throwable.printStackTrace()
|
import java.io.PrintStream;
public class ApplicationException extends Exception {
private Throwable exception;
public ApplicationException(String message,
Throwable exception) {
super(message);
this.exception = exception;
}
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(PrintStream out) {
synchronized(out) {
super.printStackTrace(out);
if (exception != null) {
out.print("Caused by: ");
exception.printStackTrace(out);
}
}
}
}
|
} catch (Exception e) {
throw new ApplicationException("Oh, no!", e);
}
|
|