Chaining Exceptions

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(
    at TestExceptions.main(
Caused by: java.lang.Exception
    at TestExceptions.methodTwo(
    at TestExceptions.methodOne(
    at TestExceptions.thisWillFail(
    at TestExceptions.main(

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()


public class ApplicationException extends Exception {
    private Throwable exception;

    public ApplicationException(String message,
                                Throwable exception) {
        this.exception = exception;

    public void printStackTrace() {

    public void printStackTrace(PrintStream out) {
        synchronized(out) {
            if (exception != null) {
                out.print("Caused by: ");
        } catch (Exception e) {
            throw new ApplicationException("Oh, no!", e);