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

Omitting the Catch and Finally Blocks

Try-with-resources doesn't require catch or finally; resources close automatically before exceptions propagate.

Omitting the Catch and Finally Blocks

You'll learn that try-with-resources automatically closes resources and lets exceptions propagate, so you often don't need catch or finally blocks at all.

The Old Way Was Verbose

Before try-with-resources, you needed a finally block to ensure resources closed properly. This made even simple resource handling code lengthy and repetitive.

Try-With-Resources Does Cleanup for You

Here's the beautiful part: try-with-resources handles resource cleanup automatically, even when exceptions occur. You can write just the try part with your resources, and the close() method gets called automatically before any exception leaves the block.

// Valid and complete!
try (FileReader reader = new FileReader("data.txt")) {
    // use reader
    int data = reader.read();
}
// reader.close() already called automatically
// Exception propagates naturally if one occurred

No catch, no finally—perfectly legal. If an exception happens, the resource still closes before the exception propagates up the call stack.

When You Still Need Catch or Finally

You only add catch blocks when you want to handle the exception locally:

try (FileReader reader = new FileReader("data.txt")) {
    int data = reader.read();
} catch (IOException e) {
    System.out.println("Failed to read file: " + e.getMessage());
}

You only add finally when you need additional cleanup beyond closing the resource (rare, since closing is the main reason finally existed).

Think of It Like Autopilot

It's like a car with auto-parking: the car handles parking (resource closing) automatically. You only take manual control (catch/finally) when you want to do something extra.

Key Takeaway: Try-with-resources doesn't require catch or finally blocks—resources close automatically and exceptions propagate naturally, making your code cleaner and safer.