Behavior of try-with-resources when a resource's close() throws an Error
0 reputation · 16 Jan 2025, 16:54 UTC
Goal
Determine whether the Java Language Specification defines the handling of Errors thrown from a resource's close() method inside a try-with-resources block, specifically whether such Errors are treated as suppressed exceptions accessible via Throwable.getSuppressed().
Uncertainty
The specification for try-with-resources (JLS §14.20.3) states that any exception thrown from close() is suppressed and added to the list of suppressed exceptions, but it does not explicitly restrict the thrown type to Exception or IOException. It is unclear whether Errors are subject to the same suppression mechanism or if they bypass it and propagate as the primary exception.
Questions
- Does the JVM treat an Error thrown from close() as a suppressed exception that appears in Throwable.getSuppressed()?
- If not, what is the exact propagation behavior (e.g., does the Error become the primary exception, overriding any existing exception from the try block)?
- Are there any version‑specific differences in this behavior between Java SE 7 and later releases?