简体   繁体   中英

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). 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? 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.
It is related to the close() operation that is necessarily invoked in a try-with-resources statement before allowing the method to return.

I didn't find a specific part of the JLS that specifies a case with the return.
So you have to consider that the general explanation is applicable :

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.

Note that without try-with-resources , you would probably write this code :

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.
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. But it is not your question, so let me favor this view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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