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

The Classic finally Block Pattern

Reviewing the pre-Java 7 pattern of closing resources in finally blocks and its verbosity and complexity.

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:

  1. Null check required: You must check if the resource was actually initialized
  2. Nested try-catch: The close() method itself throws exceptions, requiring another try-catch inside finally
  3. Verbose: Simple resource cleanup requires 7+ lines of boilerplate
  4. 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.