Why should I use finally to close resources?

In most cases, the only thing I see for the finally block being used 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 scope ends with a closing block, why should we close it at the end?

+5
source share
5 answers

Because garbage collection is not the same as cleaning up resources.

For example, if you have a JDBC connection object that is out of scope, there is no signal to the database server indicating that open cursors and connections are no longer needed. Without these messages, you end up running out of cursors and connections.

. .

+18

, - , FileInputStream, , Java .

f , ( try), , - , - .

, ( , , ), .

Java RAII , ++; , ++.

+6

, , , . finally , / .

+1

, Java , , . , , , , .

, java.io.File .

0

try catch, , , catch, catch , , . , - , , .

0
source

All Articles