Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try/finally without catch with return statement? [duplicate]

Why the result of the following code is 3, why the finally get to terminate and get out of the method even tho the compiler checks try first and why the return in try doesn't terminate the method?

public int returnVal(){ 
    try{
        return 2;
    }
    finally{
        return 3;
    }
}
like image 291
Ahmad Sanie Avatar asked Jan 11 '16 15:01

Ahmad Sanie


People also ask

Is it possible to have a try without catch and finally?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.

Does return bypass finally?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java. If we call the System.

Can we use return statement in finally block?

Yes you can write the return statement in a finally block and it will override the other return value. The output is always 2, as we are returning 2 from the finally block. Remember the finally always executes whether there is a exception or not.

What happens if both a catch and a finally block define return statement?

If both catch and finally return, the receiving method will get the returned value from the finally block.


1 Answers

See JLS 14.17

It can be seen, then, that a return statement always completes abruptly.

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the method or constructor whose try blocks or catch clauses contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

Espacially check the phrases attempts to transfer control and the last sentence. The try return attempts to transfer the controll, aftwerwards the finally disrupt the transfer of control initiated by a return statement.

In other words, the try attempts to transfer the controll, but since the execution of the finally block is still open for execution and contains a return statement the attempted transfer of controll in the finally block has a higher preceding. That´s why you see the value 3, which is returned inside the finally block.

like image 182
SomeJavaGuy Avatar answered Oct 17 '22 00:10

SomeJavaGuy