尝试这段代码。为什么getValueB()返回1而不是2?毕竟,递增两次被调用两次。
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?
}
}
最佳答案
是的,但是返回值是在第二次调用之前确定的。
返回的值由该时间点的return语句中的表达式求值确定,而不是“仅在执行离开方法之前”。
从section 14.17 of the JLS:
然后按照section 14.20.2 of the JLS将执行转移到finally
块。但是,这不会重新评估return语句中的表达式。
如果您的finally块是:
finally { return increment(); }
那么新的返回值将是该方法的最终结果(根据14.20.2节)-但您并未这样做。