简体   繁体   English

尝试资源中的流控制关闭异常

[英]Flow Control in try-with-resources close exception

I couldn't find the answer with a Google search, so I ask it here (for navigation help). 我无法通过Google搜索找到答案,因此请在此处提出要求(以获取导航帮助)。 If one were to return a value in a try-with-resources block, the close method throws an exception, I handle the exception without throwing, and resume execution, is the value I tried to return returned, or does execution resume after the catch block? 如果要在try-with-resources块中返回一个值,则close方法会引发异常,我不抛出异常就处理该异常,然后恢复执行,是我尝试返回的值,还是在catch之后恢复执行块? For example: 例如:

public static int test(){
    class Foo implements AutoCloseable{
        @Override
        public void close(){
            throw new RuntimeException();
        }
    }
    try(Foo foo = new Foo()){
        return 1;
    }
    catch (RuntimeException e){
        //handle exception without throwing
    }
    return 2;
}

The exception throwing causes the execution to reach the catch statement and so 2 is returned. 引发异常导致执行到达catch语句,因此返回2
It is related to the close() operation that is necessarily invoked in a try-with-resources statement before allowing the method to return. 它与close()操作有关,该操作在允许方法返回之前必须在try-with-resources语句中调用。

I didn't find a specific part of the JLS that specifies a case with the return. 我没有找到JLS的特定部分来指定返回的情况。
So you have to consider that the general explanation is applicable : 因此,您必须考虑以下一般解释:

14.20.3. 14.20.3。 try-with-resources 尝试与-资源

... ...

If all resources initialize successfully, the try block executes as normal and then all non-null resources of the try-with-resources statement are closed. 如果所有资源都成功初始化,则try块将正常执行,然后try-with-resources语句的所有非空资源都将关闭。

Note that without try-with-resources , you would probably write this code : 请注意,如果没有try-with-resources ,您可能会编写以下代码:

try(Foo foo = new Foo()){
    return 1;
}
catch (RuntimeException e){
    //handle exception without throwing
}
return 2;

in this way : 通过这种方式 :

try{
    Foo foo = new Foo();
    foo.close(); // handled automatically by  try-with-resources 
    return 1;
}       
catch (RuntimeException e){
    //handle exception without throwing
}
return 2;

So it should make sense why 1 cannot be returned. 因此,为什么不能返回1应该很有意义。
Note that the code generated by the compiler by a try-with-resources is much longer and more complex than the pseudo equivalence I provided because of suppressed exceptions. 请注意,由于抑制了异常,编译器通过try-with-resources生成的代码比我提供的伪等效项长得多,也更复杂。 But it is not your question, so let me favor this view. 但这不是您的问题,所以让我赞成这种观点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM