Exceptions: wrapping a cause with new Exception(message, cause) preserves it under getCause

The two-argument exception constructor stores the original failure as the cause, so a higher-level exception can add context while getCause still returns the low-level exception that actually happened first.

Code
try {
    try {
        Integer.parseInt("not-a-number");
    } catch (NumberFormatException original) {
        throw new IllegalStateException("failed to load configuration", original);
    }
} catch (IllegalStateException wrapped) {
    System.out.println("Outer: " + wrapped.getClass().getSimpleName() + ": " + wrapped.getMessage());
    Throwable cause = wrapped.getCause();
    System.out.println("Cause: " + cause.getClass().getSimpleName() + ": " + cause.getMessage());
}
Output
Outer: IllegalStateException: failed to load configuration
Cause: NumberFormatException: For input string: "not-a-number"
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms