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.
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++;
}
Level 0: RuntimeException: request failed
Level 1: IllegalStateException: parse stage failed
Level 2: NumberFormatException: bad digit
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