Combining Try-With-Resources and Finally
What you'll learn: How to add a finally block to try-with-resources for additional cleanup that happens after automatic resource closure.
The Core Idea
Try-with-resources automatically closes your resources, but sometimes you need extra cleanup that goes beyond just closing files or streams. You can add a finally block to your try-with-resources statement, and it will execute after all declared resources have been automatically closed.
Think of it like leaving a hotel room: try-with-resources turns off the lights and locks the door automatically (closes resources), but you might still want to check one last time that you didn't forget anything in the lobby (additional cleanup in finally).
Execution Order
The sequence is predictable and reliable:
- Try block executes your main logic
- Resources are closed automatically (in reverse order of declaration)
- Catch block handles exceptions (if present and needed)
- Finally block runs for additional cleanup
When This Is Useful
Use a finally block with try-with-resources when you need to:
- Log that an operation completed
- Update status flags or counters
- Release non-AutoCloseable resources
- Perform cleanup that's independent of the AutoCloseable resources
Example Pattern
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
// Read and process file
String line = reader.readLine();
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
} finally {
System.out.println("File operation completed, logging activity...");
// Additional cleanup: logging, status updates, etc.
}
The finally block always runs—whether an exception occurred or not—but only after the BufferedReader has been automatically closed.
Key Takeaway: A finally block in try-with-resources executes after automatic resource closure, providing a reliable place for additional cleanup tasks that aren't handled by the resources themselves.