When a constructor does not accept a cause, initCause can set one later, but only if no cause was already given; calling it a second time throws IllegalStateException, which this snippet catches to show the rule.
Exception outer = new Exception("outer failure");
outer.initCause(new RuntimeException("root cause"));
System.out.println("Cause: " + outer.getCause().getMessage());
try {
outer.initCause(new RuntimeException("second attempt"));
} catch (IllegalStateException e) {
System.out.println("Second initCause: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
Cause: root cause
Second initCause: IllegalStateException: Can't overwrite cause with java.lang.RuntimeException: second attempt
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