Multiple Resource Suppression
What you'll learn: How Java handles the scenario when multiple AutoCloseable resources each throw exceptions during their close() operations.
The Cascading Close Problem
When you use try-with-resources with multiple resources, Java closes them in reverse order of initialization. But what happens when more than one resource throws an exception during closing? Java can't throw multiple exceptions at once—it needs a strategy to preserve all the error information.
How Multiple Suppression Works
When several resources throw exceptions during closing:
- The first exception thrown becomes the primary exception
- All subsequent exceptions from closing remaining resources become suppressed exceptions attached to the primary
- The primary exception propagates up with all suppressed exceptions attached
Think of it like a chain reaction: if three dominoes fall and each makes a different noise, you report the first noise as the main event, but you don't ignore the other two—you attach them as "additional notes."
Example Scenario
Imagine three resources: ResourceA, ResourceB, and ResourceC, initialized in that order. They close in reverse (C, B, A). If:
ResourceC.close()throwsExceptionC→ becomes primaryResourceB.close()throwsExceptionB→ suppressedResourceA.close()throwsExceptionA→ suppressed
The exception that propagates out is ExceptionC, with ExceptionB and ExceptionA retrievable via getSuppressed(), in that order.
Why This Matters
Without suppression, you'd lose critical diagnostic information. Multiple resources failing to close often indicates a serious system issue (out of memory, file system errors, etc.), and seeing all the failures helps you diagnose the root cause.
Key Takeaway: When multiple try-with-resources throw during closing, the first close exception becomes primary, and all subsequent close exceptions are attached as suppressed exceptions, preserving complete error information.