Exceptions: a failing close() in try-with-resources becomes a suppressed exception

If the try block throws and a resource's close() also throws while cleaning up, the close() exception does not replace the original; it is attached to it as a suppressed exception instead, so nothing is lost.

Code
class FlakyResource implements AutoCloseable {
    public void close() {
        throw new IllegalStateException("close failed");
    }
}
try {
    try (FlakyResource r = new FlakyResource()) {
        throw new RuntimeException("primary failure");
    }
} catch (RuntimeException e) {
    System.out.println("Primary: " + e.getClass().getSimpleName() + ": " + e.getMessage());
    for (Throwable suppressed : e.getSuppressed()) {
        System.out.println("Suppressed: " + suppressed.getClass().getSimpleName() + ": " + suppressed.getMessage());
    }
}
Output
Primary: RuntimeException: primary failure
Suppressed: IllegalStateException: close failed
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms