从finally块返回时Java的奇怪行为 [英] Java's strange behavior while returning from finally block

查看:109
本文介绍了从finally块返回时Java的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试这段代码.为什么getValueB()返回1而不是2?毕竟,递增()函数被调用两次.

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

推荐答案

毕竟,递增函数被调用了两次.

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

来自JLS的第14.17节:

带有Expression的return语句试图将控制权转移到包含它的方法的调用者; Expression的值成为方法调用的值.更准确地说,执行这种return语句首先会评估表达式.如果由于某种原因对表达式的求值突然完成,则return语句由于该原因而突然完成.如果对Expression的求值正常完成,产生一个值V,则return语句突然完成,原因是返回值为V.

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.

如果您的finally块是:

If your finally block were:

finally { return increment(); }

然后,新的返回值将是该方法的最终结果(根据14.20.2节)-但您并未这样做.

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.

这篇关于从finally块返回时Java的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆