What is exception chaining in Java and why keep the cause?
Exception chaining wraps a low-level exception inside a higher-level one using the cause argument, so callers get a meaningful message and the stack trace still shows the original failure through getCause().
Explain it simply
When a courier tells you "delivery failed", you want the reason underneath: wrong pin code, house locked, or road flooded. Exception chaining attaches that underlying reason to the message you actually show.
Example
static int readAge(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new IllegalStateException("Age in the form is invalid", e); // e is the cause
}
}
try {
readAge("x1");
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // prints: Age in the form is invalid
System.out.println(e.getCause().getClass().getSimpleName()); // prints: NumberFormatException
}What to say in the interview
"A service layer should not leak a low-level exception like SQLException to the UI. I wrap it in a business exception, such as OrderFailedException, and pass the original as the cause. Passing only the message throws away the original stack trace, which makes production bugs very hard to trace. The constructor new X(message, cause) or initCause does the linking, and the logged stack trace then shows 'Caused by:' lines."
Common mistakes
- Writing
throw new RuntimeException(e.getMessage()), which loses the original stack trace. - Wrapping so many times that the real problem is buried six levels deep.