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

Combining Try-With-Resources and Catch

Add catch blocks after try-with-resources to handle exceptions thrown during resource usage.

Combining Try-With-Resources and Catch

What you'll learn: How to add catch blocks after try-with-resources statements to handle exceptions that occur while using managed resources.


The Core Idea

While try-with-resources automatically closes resources for you, it doesn't automatically handle exceptions that occur during resource usage. You can (and often should) add catch blocks right after the try-with-resources statement to handle these exceptions gracefully, just like with regular try-catch blocks.

Think of it like this: try-with-resources is your automatic door closer, but you still need a plan for what to do if something goes wrong while the door is open.

How It Works

The syntax combines the resource declaration in parentheses with traditional catch blocks:

try (AutoCloseable resource = new SomeResource()) {
    // Use the resource
    // Exception might be thrown here
} catch (SpecificException e) {
    // Handle the exception
    System.out.println("Error: " + e.getMessage());
}

The resource is still guaranteed to close, whether an exception occurs or not. The catch block simply gives you a chance to respond to problems that happen during usage.

Multiple Catch Blocks Still Work

You can use multiple catch blocks, multi-catch syntax, and all the exception-handling techniques you've learned:

try (AutoCloseable resource = new SomeResource()) {
    // Risky operations
} catch (IOException e) {
    System.out.println("IO problem: " + e.getMessage());
} catch (IllegalStateException e) {
    System.out.println("Invalid state: " + e.getMessage());
}

The resource closes before any catch block executes, ensuring proper cleanup even when handling errors.

Key Takeaway:
Try-with-resources and catch blocks work together seamlessly—the resource closes automatically, then your catch blocks handle any exceptions that occurred during usage.