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

Accessing Suppressed Exception Details

Iterating through suppressed exceptions to log or handle each one individually for debugging.

Accessing Suppressed Exception Details

You'll learn how to iterate through suppressed exceptions to examine and log each one individually for thorough debugging.

The Core Idea

When you use try-with-resources and multiple exceptions occur (one during normal execution, others during resource closing), Java stores the "hidden" exceptions as suppressed exceptions. You already know how to retrieve them using getSuppressed(), but often you need to examine each suppressed exception in detail—its message, type, stack trace, and cause—to understand what went wrong during resource cleanup.

Think of it like opening a package that contains multiple damaged items. You don't just want to know "some things broke"—you want to inspect each broken item individually to understand the full extent of the problem.

Iterating Through Suppressed Exceptions

The getSuppressed() method returns an array of Throwable objects. You can loop through this array to access each suppressed exception's details:

try (MyResource res1 = new MyResource();
     MyResource res2 = new MyResource()) {
    throw new IOException("Primary failure");
} catch (Exception e) {
    System.out.println("Primary: " + e.getMessage());
    
    // Iterate through all suppressed exceptions
    Throwable[] suppressed = e.getSuppressed();
    for (int i = 0; i < suppressed.length; i++) {
        System.out.println("Suppressed #" + (i + 1) + ": " + 
                           suppressed[i].getMessage());
        System.out.println("  Type: " + 
                           suppressed[i].getClass().getName());
        // Could also call printStackTrace() on each
    }
}

This allows you to log every failure that occurred, not just the primary one, giving you complete visibility into cascading resource cleanup failures.

Key Takeaway:
Loop through the array returned by getSuppressed() to individually examine each suppressed exception's type, message, and stack trace for comprehensive debugging.