Exceptions: getSuppressed exposes exceptions hidden behind the one that propagated

getSuppressed returns an array of every exception that try-with-resources or addSuppressed attached to the exception that actually propagated, so cleanup failures remain visible instead of vanishing.

Code
RuntimeException primary = new RuntimeException("main failure");
primary.addSuppressed(new IllegalStateException("cleanup A failed"));
primary.addSuppressed(new IllegalArgumentException("cleanup B failed"));
System.out.println("Primary: " + primary.getMessage());
for (Throwable s : primary.getSuppressed()) {
    System.out.println("Suppressed: " + s.getClass().getSimpleName() + ": " + s.getMessage());
}
Output
Primary: main failure
Suppressed: IllegalStateException: cleanup A failed
Suppressed: IllegalArgumentException: cleanup B 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