Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java's strange behavior while returning from finally block

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

    public class ReturningFromFinally
    {
      public static int getValueA() // This returns 2 as expected
      {
         try     { return 1; }
         finally { return 2; }
      }

      public static int getValueB() // I expect this to return 2, but it returns 1
      {
        try     { return increment(); }
        finally { increment(); }
      }

      static int counter = 0;

      static int increment()
       {
          counter ++;
          return counter;
       }

      public static void main(String[] args)
      {
          System.out.println(getValueA()); // prints 2 as expected
          System.out.println(getValueB()); // why does it print 1?
      }
}
like image 812
CodeBlue Avatar asked Aug 15 '12 21:08

CodeBlue


2 Answers

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.

like image 124
Jon Skeet Avatar answered Sep 28 '22 17:09

Jon Skeet


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.

like image 36
obataku Avatar answered Sep 28 '22 16:09

obataku