When Suppression Occurs
What you'll learn: You'll discover the exact scenarios in which Java suppresses exceptions from close() methods when using try-with-resources.
The Collision Scenario
Exception suppression happens when two exceptions collide: one from your try block and another from the automatic close() call. Java must decide which exception to propagate and which to suppress.
The rule is simple: If an exception is thrown from the try block, and then another exception is thrown while closing resources, the close exception gets suppressed. The try block exception "wins" and becomes the primary exception.
Why This Order?
Think of it like a car accident investigation. If your brakes fail (try block problem) and then your airbag malfunctions during the crash (close problem), investigators focus on the brake failure—it was the original cause. The airbag issue matters, but it's secondary.
When Suppression Actually Occurs
Scenario 1: Exception in try block + exception in close() = close exception suppressed
Scenario 2: No exception in try block + exception in close() = close exception propagates normally (no suppression)
Scenario 3: Multiple resources, exceptions in multiple close() calls + exception in try block = all close exceptions suppressed
Example in Plain English
Imagine you're reading a file (try block) and an error occurs. Then, while Java automatically closes the file, the close operation also fails. You'll receive the reading error as the main exception, with the closing error attached as suppressed. If reading succeeded but closing failed, you'd simply get the closing error—nothing to suppress.
Key Takeaway: Exception suppression occurs when a try-with-resources block throws an exception from the try body and one or more close() methods also throw exceptions. The try block exception takes priority, and close exceptions are suppressed but remain accessible via getSuppressed().