Reputation: 1645
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;
}
Upvotes: 0
Views: 420
Reputation: 131356
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 :
...
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.
Upvotes: 1