Search code examples
javaexceptionreturntry-catch

try/finally without catch with return statement?


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;
    }
}

Solution

  • 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.