资源java7,java-7 – 我正确地使用Java 7尝试资源

这是正确的,没有catch子句的要求。 Oracle java 7 doc表示资源将被关闭,而不管是否实际抛出异常。

只有当您想对异常作出反应时,才应使用catch子句。 catch子句将在资源关闭后执行。

The following example reads the first line from a file. It uses an

instance of BufferedReader to read data from the file. BufferedReader

is a resource that must be closed after the program is finished with

it:

static String readFirstLineFromFile(String path) throws IOException {

try (BufferedReader br =

new BufferedReader(new FileReader(path))) {

return br.readLine();

}

} // In this example, the resource declared in the try-with-resources statement is a BufferedReader.

… Because the BufferedReader instance is declared in a

try-with-resource statement, it will be closed regardless of whether

the try statement completes normally or abruptly (as a result of the

method BufferedReader.readLine throwing an IOException).

编辑

关于新编辑的问题:

Java 6中的代码执行catch和之后的finally块。这导致资源仍然可能在catch块中打开。

在Java 7语法中,资源在catch块之前关闭,因此资源在catch块执行期间已经关闭。这在上面的链接中记录:

In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值