Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...