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

Primary vs Suppressed Exceptions

Understanding which exception becomes primary and which get suppressed in try-with-resources execution flow.

Primary vs Suppressed Exceptions

You'll learn how to identify which exception becomes the primary (thrown) exception and which exceptions get suppressed in try-with-resources.

When multiple exceptions occur during try-with-resources execution, Java must choose one as the "primary" exception to throw, while the others become "suppressed" exceptions attached to it.

The Primary Exception Rule

The primary exception is the first exception thrown from your main try block. If an exception occurs in your business logic (the code inside the try block), that exception takes precedence and becomes primary.

Any exceptions thrown later during resource cleanup (close() calls) are automatically suppressed and attached to the primary exception.

When the close() Exception Becomes Primary

If your try block completes successfully but a resource's close() method throws an exception, that becomes the primary exception — because it's the only exception that occurred.

If multiple resources fail to close, the first close exception becomes primary, and subsequent close exceptions are suppressed.

Think of It Like This

Imagine you're at a restaurant: if you get food poisoning (try block exception), that's the primary problem. If the waiter also drops your plate while cleaning up (close exception), that's a suppressed issue. But if the meal went fine and only the plate drops, that becomes the primary problem.

// Example scenario:
try (MyResource r = new MyResource()) {
    throw new IOException("Primary!"); // This becomes primary
    // r.close() throws Exception → becomes suppressed
}

try (MyResource r = new MyResource()) {
    // No exception here
    // r.close() throws Exception → This becomes primary
}

Key Takeaway: The first exception from the try block always becomes primary; cleanup exceptions are suppressed. If no try block exception occurs, the first close exception becomes primary.