Java#39;s strange behavior while returning from finally block(从 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?
}
}
推荐答案
毕竟,increment() 函数被调用了两次.
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 语句会因为这个原因而突然完成.如果表达式的计算正常完成,产生一个值 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.
执行然后转移到 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 的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 finally 块返回时 Java 的奇怪行为
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01