Manual close() and the Risk of Exceptions
What you'll learn: Why manually calling close() in a finally block is error-prone and how exceptions during closure can mask original errors.
The Hidden Danger of Manual Cleanup
Before try-with-resources existed, developers had to manually close streams in finally blocks to ensure cleanup. This approach seems straightforward, but it harbors a dangerous pitfall: the close() method itself can throw exceptions.
The Problem Scenario
Imagine you're reading a file and an IOException occurs. You catch it, then call close() in your finally block—but close() also throws an exception. Now you have two exceptions: the original one from your read operation and a new one from closing. The second exception suppresses the first, hiding the real cause of your problem.
FileInputStream fis = null;
try {
fis = new FileInputStream("data.txt");
// ... work with stream ...
// IOException occurs here!
} catch (IOException e) {
System.err.println("Read failed: " + e.getMessage());
} finally {
if (fis != null) {
fis.close(); // Can throw IOException!
// If it does, original exception is lost
}
}
The Double Try-Catch Pattern
To properly handle this, you need a nested try-catch inside the finally block:
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.err.println("Close failed: " + e.getMessage());
}
}
}
This verbose pattern ensures closing exceptions don't mask earlier errors, but it's clunky and easy to forget.
Key Takeaway: Manually closing streams in finally blocks requires nested try-catch to prevent close() exceptions from suppressing the original exception—a complex pattern that makes try-with-resources vastly superior for resource management.