Java's strange behavior while returning from finally block

后端 未结 6 2188
梦谈多话
梦谈多话 2021-01-02 03:26

Try this piece of code. Why does getValueB() return 1 instead of 2? After all, the increment() function is getting called twice.

    public class ReturningF         


        
6条回答
  •  忘掉有多难
    2021-01-02 03:46

    After all, the increment() function is getting called twice.

    Yes, but the return value is determined before the second call.

    The value returned is determined by the evaluation of the expression in the return statement at that point in time - not "just before execution leaves the method".

    From section 14.17 of the JLS:

    A return statement with an Expression attempts to transfer control to the invoker of the method that contains it; the value of the Expression becomes the value of the method invocation. More precisely, execution of such a return statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the return statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.

    Execution is then transferred to the finally block, as per section 14.20.2 of the JLS. That doesn't re-evaluate the expression in the return statement though.

    If your finally block were:

    finally { return increment(); }
    

    then that new return value would be the ultimate result of the method (as per section 14.20.2) - but you're not doing that.

提交回复
热议问题