Course contentsShow
← Java
Lesson 841 of 2,87020. Try-With-Resources and Resource ManagementFree lesson

The getSuppressed() Method

Using Throwable.getSuppressed() to retrieve an array of all suppressed exceptions from a caught exception.

The getSuppressed() Method

You'll learn how to retrieve suppressed exceptions from a caught exception using Throwable.getSuppressed().

When using try-with-resources, additional exceptions thrown during resource closing can be automatically suppressed if an exception already occurred in the main try block. But these suppressed exceptions aren't lost—Java stores them, and you can retrieve them.

Accessing Suppressed Exceptions

The Throwable class provides the getSuppressed() method, which returns an array of all exceptions that were suppressed. This allows you to examine what went wrong during resource cleanup, even when another exception took priority.

try {
    // Resource that throws exception in close()
} catch (Exception e) {
    System.out.println("Main exception: " + e.getMessage());
    
    Throwable[] suppressed = e.getSuppressed();
    if (suppressed.length > 0) {
        System.out.println("Suppressed exceptions:");
        for (Throwable t : suppressed) {
            System.out.println("  - " + t.getMessage());
        }
    }
}

Why This Matters

Think of suppressed exceptions like footnotes in an error report. The main exception is the headline, but the suppressed exceptions provide additional context about what else went wrong during cleanup. Without getSuppressed(), you'd never see these important details.

The method returns a Throwable[] array, which may be empty if no exceptions were suppressed. You can loop through this array to log, analyze, or handle each suppressed exception individually.

When to Use It

Use getSuppressed() when debugging complex resource management issues, when comprehensive error logging is required, or when you need to understand the full chain of failures in try-with-resources blocks.

Key Takeaway: Use Throwable.getSuppressed() to retrieve an array of all suppressed exceptions, giving you complete visibility into failures that occurred during automatic resource closing.