Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Throwable.getSuppressed() — suppressed exceptions

Call `getSuppressed()` on the primary exception to inspect attached exceptions, such as a resource-closing failure that occurred after the `try` body failed.

Version: Java SE 21

Syntax

public final Throwable[] getSuppressed()

Throwable.getSuppressed is a no-argument instance method on java.lang.Throwable. It returns a Throwable[] containing the suppressed exceptions attached directly to the object you call it on. If none are attached or suppression is disabled for that object, it returns an empty array, not null. Changing the returned array does not change the stored list.

When the try body throws and automatic close() throws a different exception, try-with-resources propagates the body exception and, if suppression is enabled, attaches the close exception to it. Call getSuppressed() on the caught primary exception, not on the close exception: the close exception is not suppressed by itself.

If the body completes normally and only one close throws, that close exception propagates as the primary exception. Resources close in reverse initialization order. If several closes throw distinct exceptions after the body completes normally, the first exception in closing order is primary, and the others are attached to it if suppression is enabled.

getCause() returns the exception's cause (or null), not an array of additional failures. The same object can have both a cause and suppressed exceptions.

Examples

public class Main {
    public static void main(String[] args) {
        try (AutoCloseable resource = () -> {
            throw new IllegalStateException("close failed");
        }) {
            throw new IllegalStateException("body failed");
        } catch (Exception primary) {
            System.out.println("Primary: " + primary.getMessage());
            Throwable[] suppressed = primary.getSuppressed();
            System.out.println("Suppressed count: " + suppressed.length);
            for (Throwable secondary : suppressed) {
                System.out.println("Suppressed: " + secondary.getMessage());
                System.out.println("Its suppressed count: " + secondary.getSuppressed().length);
            }
        }
    }
}

Result

Primary: body failed
Suppressed count: 1
Suppressed: close failed
Its suppressed count: 0

The first three lines show the primary exception and one attached `close()` exception. The last line shows that the `close()` exception has no suppressed exceptions of its own in this example.

Related lessons

  • Java · Lesson 31 · Intermediate · Version: 2

Sources