What Are Suppressed Exceptions?
You'll learn how try-with-resources handles multiple exceptions that occur during resource cleanup, and why some exceptions get "hidden" behind others.
The Multiple Exception Problem
When you use try-with-resources, exceptions can occur in two places: during the main try block and during the automatic close() call. If both happen, Java has to decide which exception to throw to your code.
Consider this scenario: Your code attempts to write to a file, throws an IOException, and then when try-with-resources tries to close the file, another IOException occurs in the close() method. You can't throw both exceptions at once, so which one matters more?
Primary vs Suppressed Exceptions
Java's solution: the exception from your try block is primary (the one that gets thrown), and exceptions from close() are suppressed (attached but hidden).
Think of it like reporting a car accident. The main crash (your try block exception) is the primary incident. If the airbag also malfunctioned during the crash (close() exception), that's important information, but it's secondary to the main event.
Why This Matters
Without suppression, the close() exception would completely hide your original exception—you'd lose critical debugging information about what actually went wrong in your code. Suppression preserves both pieces of information while clearly identifying which problem triggered the failure.
You can access suppressed exceptions using the getSuppressed() method from the Throwable class, which returns an array of all exceptions that were suppressed during resource cleanup.
Key Takeaway: Suppressed exceptions allow try-with-resources to preserve all exception information when both the main code and resource cleanup fail, with the try block exception taking priority as the primary exception thrown.