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.
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());
}
Outer: IllegalStateException: failed to load configuration
Cause: NumberFormatException: For input string: "not-a-number"
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