Java Java7

Throwable.addSuppressed() and getSuppressed()

Throwable.addSuppressed() and getSuppressed()

Throwable.addSuppressed() and getSuppressed()

Suppressed exceptions are a Java 7 feature that allows multiple exceptions to be tracked when a primary exception is thrown, particularly within try-with-resources.

How it Works

If a resource close() throws an exception after the try block already threw one, the close() exception is 'suppressed' but attached to the primary exception. These can be retrieved via getSuppressed().

Java Example

public class SuppressedExample {
    public static void main(String[] args) {
        try {
            throw new Exception("Primary");
        } catch (Exception e) {
            e.addSuppressed(new Exception("Suppressed"));
            for (Throwable t : e.getSuppressed()) {
                System.out.println("Caught: " + t.getMessage());
            }
        }
    }
}

Output

Caught: Suppressed

Key Points

  • Tracks hidden exceptions
  • Crucial for try-with-resources
  • Available in the Throwable class
  • Prevents loss of error information
Topics: Java Java7
← Newer Post Older Post →