尝试资源的资源范围 [英] Try-with-resources scope of resource

查看:149
本文介绍了尝试资源的资源范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7 try -with-resources 构造中,我可以在 try 语句,当超出范围时,它将自动关闭。

In the try-with-resources construct of Java 7, I can declare a resource in the try statement, and it will be closed automatically when it goes out of scope.

但是,我没有找到资源范围的任何指示可用。具体来说,它可以在它被声明的try块的 catch / finally 块中提供。

However, I don't find any indication of the scope of the resource made available. Specifically, is it available in the catch/finally blocks of the try block where it is declared?

我在 Eclipse Kepler 中尝试过以下操作,但却给人一种混合的印象:

I tried the following in Eclipse Kepler, but it's giving a mixed impression:

资源变量由内容辅助(代码完成)提供:

快速修复建议更改为资源变量,但这递归地产生相同的问题它试图修复:

Quick Fix suggests changing to resource variable, but this recursively produces the same problem it's trying to fix:

我想知道正确范围限制是什么,然后在Eclipse Bug Tracker 。

I would like to know what the correct scope limitation is, before raising a bug in the Eclipse Bug Tracker.

推荐答案

此语法称为 扩展的试用资源

This syntax is called Extended try-with-resources

按< a href =http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.3> JLS :

try ResourceSpecification
    Block
Catchesopt
Finallyopt

将被翻译成:

try {
    try ResourceSpecification
        Block
}
Catchesopt
Finallyopt

所以在您的示例中,您的资源将被限制为内部try块,因此不适用于外部 try / catch / finally

So, in your example, your resource will be limited to inner try block, so not available for outer try/catch/finally.

编辑:


我的问题没有嵌套的尝试块

my question does not have nested try blocks

通过在代码中明确添加catch / finally块,您将引入嵌套的try块。

By explicitly adding catch/finally block in your code, you are introducing nested try blocks.

这篇关于尝试资源的资源范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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