[ACCEPTED]-How do I append to a Java exception?-stack-trace

Accepted answer
Score: 32

Exceptions can be chained:

try {
    ...
} catch (Exception ex) {
    throw new Exception("Something bad happened", ex);
}

It makes original 3 exception the cause of the new one. Cause of 2 exception can be obtained using getCause(), and calling 1 printStackTrace() on the new exception will print:

Something bad happened
... its stacktrace ...
Caused by:
... original exception, its stacktrace and causes ...
Score: 4

Typically you throw a new exception which 7 includes the old exception as a "cause". Most 6 exception classes have a constructor which 5 accept a "cause" exception. (You can get 4 at this via Throwable.getCause().)

Note that you should almost 3 never be catching just Exception - generally you 2 should be catching a more specific type 1 of exception.

Score: 2

Just use a different constructor:

Exception(String message, Throwable cause)

The message 3 is your "two cent" and you include the catched 2 exception, which will be shown in a stacktrace 1 printout

Score: 0

You can add the underlying cause to a newly 1 created exception:

    throw new Exception("Failed to process input [" 
                + ((null == input) ? "null" : input)
                + "] at index " + i + ": " + Arrays.toString(input_array) 
                + "\n" + e.getMessage(), e);

More Related questions