为什么我需要最终使用来关闭资源? [英] Why do I need to use finally to close resources?

查看:125
本文介绍了为什么我需要最终使用来关闭资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数情况下,我唯一看到的finally块用于

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();
}

我的问题是,如果f的范围以封闭块结束,为什么我们要需要在finally中关闭它吗?

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.

例如,如果JDBC连接对象超出范围,则没有信号发送到数据库服务器以指示打开的游标和连接不是需要更久。如果没有这些消息,您最终将耗尽可用的游标和连接数。

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.

这篇关于为什么我需要最终使用来关闭资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆