CKTIS / Java
Throwable.getCause(): walking the cause chain
`Throwable.getCause()` returns the immediate cause. Call it on each successive object to walk from the outer exception to the last available cause.
Version: Java SE 21
Syntax
public Throwable getCause()
Throwable cause = failure.getCause();
for (Throwable current = failure; current != null; current = current.getCause()) {
// Process current.
}Throwable.getCause() is a no-argument instance method on java.lang.Throwable. It returns the immediate cause as a Throwable, or null if the cause is absent or unknown. When wrapping an exception, pass the original exception to a constructor that accepts a cause to preserve the link.
Start with the outer exception. While current != null, process the current object and advance with current = current.getCause(). The first iteration includes the outer exception itself. The last object visited is not necessarily the actual root of the problem: null only tells you that no further cause is available.
Suppressed exceptions are available separately through getSuppressed(); the cause loop does not visit them. A cause chain can contain a cycle. If your code must handle arbitrary cause chains, track visited objects by reference identity, for example with an IdentityHashMap, and stop when an object is revisited.
Examples
public class CauseChainDemo {
public static void main(String[] args) {
Exception input = new Exception("Invalid port");
Exception config = new Exception("Cannot load configuration", input);
Exception startup = new Exception("Cannot start application", config);
for (Throwable current = startup; current != null; current = current.getCause()) {
System.out.println(current.getMessage());
}
}
}Result
Cannot start application Cannot load configuration Invalid port
The constructors link three objects; the program does not throw them. The loop prints the messages from `startup` through `config` to `input`. The cause of `input` is `null`, which stops the loop and is not printed.
Related lessons
- Java · Lesson 30 · Intermediate · Version: 2