All 15 Exceptions questions
More in Exceptions
Advertisement
Java › Exceptions

What is the purpose of the addSuppressed() mechanism and getSuppressed() method on Throwable, and in what specific scenario does the JVM automatically populate suppressed exceptions?

Intermediate

Answer

Suppressed exceptions handle the scenario where a try-with-resources block's body throws an exception, AND the automatic close() call on one or more resources ALSO throws an exception during cleanup -- rather than losing one of these two genuinely important pieces of information, the JVM propagates the original (primary) exception from the try block's body while automatically attaching the close()-triggered exception(s) as suppressed exceptions on it, accessible via getSuppressed(), ensuring neither failure is silently discarded even though only one exception can be the 'main' one propagating up the call stack.
try (AutoCloseable resource = () -> { throw new IOException("close failed"); }) {
    throw new RuntimeException("operation failed");  // this becomes the PRIMARY exception
}
// Catching this: e.getMessage() == "operation failed"
// e.getSuppressed()[0].getMessage() == "close failed" -- NOT lost, just attached as suppressed
Real-world example A database transaction wrapped in try-with-resources throws a business-logic exception while its connection's close() method also fails due to a broken network connection, and the resulting stack trace shows both failures clearly (the primary business exception plus the suppressed connection-close failure), giving a complete diagnostic picture instead of silently losing one of the two failures.

Common follow-ups: How would you programmatically inspect and log all suppressed exceptions attached to a caught exception?;What's the difference conceptually between a suppressed exception and a chained cause exception?