The Classic finally Block Pattern
What you'll learn: How Java developers used to guarantee resource cleanup before try-with-resources existed—and why it was painful.
The Old Way of Closing Resources
Before Java 7 introduced try-with-resources, the only reliable way to close resources like files or database connections was to use a finally block. Since finally always executes (even when exceptions occur), it was the perfect—if awkward—place to put cleanup code.
The Classic Pattern
Here's what every Java developer had to write:
FileInputStream input = null;
try {
input = new FileInputStream("data.txt");
// Use the resource
int data = input.read();
} catch (IOException e) {
// Handle exception
System.err.println("Error reading file: " + e.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
// What do we do here?
System.err.println("Error closing file: " + e.getMessage());
}
}
}
Why This Was Painful
Notice the complexity:
- Null check required: You must check if the resource was actually initialized
- Nested try-catch: The
close()method itself throws exceptions, requiring another try-catch insidefinally - Verbose: Simple resource cleanup requires 7+ lines of boilerplate
- Exception handling dilemma: If both the main code and
close()throw exceptions, which one do you report?
Think of it like needing a safety checklist with sub-checklists just to turn off a light switch when leaving a room.
Key Takeaway: The classic finally block pattern was the pre-Java 7 standard for resource cleanup, but it required verbose, nested error handling and careful null checking—making simple operations unnecessarily complex.