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

问题描述

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

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

推荐答案

是的,但返回值是在第二次调用之前确定的.

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 语句会因为这个原因而突然完成.如果表达式的计算正常完成,产生一个值 V,那么 return 语句会突然完成,原因是返回值 V.

执行然后转移到 finally 块,根据 JLS 的第 14.20.2 节.不过,这不会重新评估 return 语句中的表达式.

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 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:40