CKTIS / Java
Read suppressed exceptions with getSuppressed()
Use `getSuppressed()` to read secondary exceptions recorded on a primary exception, such as when both a `try` block and automatic resource cleanup fail.
Version: Java SE 21
Syntax
public final Throwable[] getSuppressed()
// Call on a Throwable instance:
Throwable[] suppressed = failure.getSuppressed();Throwable.getSuppressed() is a no-argument instance method on java.lang.Throwable, available since Java 7. Call it on the exception you caught to get a Throwable[] containing the suppressed exceptions recorded directly on that object.
A try-with-resources statement closes its resource automatically. If the try block and close() throw distinct exception objects, the block's exception remains primary, and the closing exception is recorded on it as suppressed if suppression is enabled. If both throw the same Throwable instance, the generated addSuppressed() call attempts self-suppression and throws IllegalArgumentException instead. If the block completes normally and close() throws the only exception, the closing exception is primary instead.
If no suppressed exceptions were recorded or suppression is disabled for that object, the method returns an empty array, never null. The method is thread-safe, and replacing elements in the returned array does not change the results of later calls.
Do not confuse this result with getCause(), which returns the cause or null if no cause exists or is known. An exception can have both a cause and suppressed exceptions.
Examples
import java.io.IOException;
public class Main {
static class DemoResource implements AutoCloseable {
@Override
public void close() throws IOException {
throw new IOException("close failed");
}
}
public static void main(String[] args) {
try (DemoResource resource = new DemoResource()) {
throw new IOException("work failed");
} catch (IOException failure) {
System.out.println("Primary: " + failure.getMessage());
for (Throwable suppressed : failure.getSuppressed()) {
System.out.println("Suppressed: " + suppressed.getMessage());
}
}
}
}Result
Primary: work failed Suppressed: close failed
The `catch` block receives `work failed`. The loop reads one suppressed exception, `close failed`, so the program prints both messages.
Related lessons
- Java · Lesson 52 · Basic · Version: 2