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.
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());
}
}
Primary: RuntimeException: primary failure
Suppressed: IllegalStateException: close failed
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