Exceptions: initCause attaches a cause after construction, and only once

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.

Code
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());
}
Output
Cause: root cause
Second initCause: IllegalStateException: Can't overwrite cause with java.lang.RuntimeException: second attempt
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