The Problem with close() in finally: Exception Suppression
You'll learn how calling close() in a finally block can accidentally hide critical exceptions from your main code.
The Hidden Danger
When you manually close streams in a finally block, you're trying to be responsible about releasing resources. But here's the problem: if both your main code and the close() method throw exceptions, only the close() exception survives—the original exception gets completely lost.
How Exception Suppression Happens
Imagine you're reading from a file and an IOException occurs mid-read. Your code jumps to the finally block to close the stream. But if close() also throws an exception (perhaps the file system is now unavailable), the second exception replaces the first one. Your original error—the one that actually matters—vanishes without a trace.
FileInputStream fis = null;
try {
fis = new FileInputStream("data.bin");
int value = fis.read(); // throws IOException (the important one!)
// ... more code
} catch (IOException e) {
// Never catches the original read() exception if close() also fails
throw e;
} finally {
if (fis != null) {
fis.close(); // throws IOException (overwrites the first!)
}
}
Why This Is Dangerous
You lose the root cause of your problem. If a disk error caused your read to fail, but then a network timeout caused close to fail, you'll only see "network timeout" in your logs. The disk error—the actual bug you need to fix—is gone forever.
The Real-World Impact
Think of it like a car accident: the crash report should describe why you crashed (brake failure), not what happened when the tow truck arrived (flat tire on the truck). Exception suppression gives you the tow truck problem instead of the brake failure.
Key Takeaway: Manually calling close() in finally blocks can suppress the original exception if close() also throws, losing critical debugging information about what actually went wrong.