Most of the time, the only thing I see a finally block used for is something like
FileInputStream f;
try{
f= new FileInputStream("sample.txt");
//something that uses f and sometimes throws an exception
}
catch(IOException ex){
/* Handle it somehow */
}
finally{
f.close();
}
My question is, if f's scope ends with the enclosing block, why do we need to close it in the finally?
Because garbage collection is not the same thing as resource cleanup.
For example, if you have a JDBC Connection object that goes out of scope, there's no signal sent to the database server to indicate that open cursors and connections are no longer needed. Without those messages, you'll eventually exhaust the number of cursors and connections available to you.
Same with file handles and any other resource. Clean up after thyself.
Well you've given a bad example - I suspect you meant something like FileInputStream
- but the basic reason is that Java doesn't have deterministic finalization.
The scope of the variable f
ends with the block it's declared in (not the try
block), but that doesn't mean there are necessarily no "live" references to the object any more - and the garbage collector will neither finalize the object nor garbage collect it in any deterministic manner.
Unless you want to leave resources hanging around for an arbitrary length of time (and delay garbage collection, as finalizers require an extra round of collection before the memory is finally released), you should explicitly close resources.
Basically Java does not support RAII in the same way that C++ does; you shouldn't try to use it as if it were C++.
because finally is called everytime, even if you get an exception raised. the finally block insure you that the file/connection will be closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With