Exceptions: walking getCause in a loop reaches the root cause of a wrapped exception

Exceptions can be wrapped several layers deep; following getCause repeatedly until it returns null walks the whole chain down to the original failure that started it all.

Code
Exception low = new NumberFormatException("bad digit");
Exception mid = new IllegalStateException("parse stage failed", low);
Exception top = new RuntimeException("request failed", mid);
Throwable current = top;
int depth = 0;
while (current != null) {
    System.out.println("Level " + depth + ": " + current.getClass().getSimpleName() + ": " + current.getMessage());
    current = current.getCause();
    depth++;
}
Output
Level 0: RuntimeException: request failed
Level 1: IllegalStateException: parse stage failed
Level 2: NumberFormatException: bad digit
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