Java's strange behavior while returning from finally block

后端 未结 6 2185
梦谈多话
梦谈多话 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:47

    See my comment.

    It would return 2 if you had finally { return increment(); }. The first return statement's expression is evaluated prior to the finally block. See Section §14.20.2 of the JLS.

    If execution of the try block completes normally, then the finally block is executed, and then there is a choice:

    • If the finally block completes normally, then the try statement completes normally.
    • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.

    Calling getValue2 (as you have it now) twice would result in 1 followed by 3.

提交回复
热议问题