我刚刚遇到以下代码:
public class TestFinally {
public static void main(String[] args) {
int returnValue = function();
System.out.println("Return value: " + returnValue);
}
public static int function() {
try {
return 1;
} catch (Exception e){
return 2;
} finally{
return 3;
}
}
}
毫无疑问,运行此代码将产生返回值:3"的输出.
It is without a doubt that running this code will yield an output of "Return value: 3".
但是,我很好奇:
非常感谢.
干杯,维恩
我在Java语言规范中找到的至少定义了你的代码片段应该返回3.当然,它没有提到JVM应该如何实现这个,以及可以做哪些优化.
What I found in the Java language specification at least defines that your code snippet should return 3. Of course, it does not mention how the JVM should implement this, and what possible optimizations one could do.
14.20 部分.2 定义了
如果 try 块的执行由于任何其他原因 R 突然完成,则执行 finally 块.然后有一个选择:
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
第 14 章的开始(section 14.1 更准确地说)指定正常和突然完成是什么.例如,具有给定值的 return
是突然完成.
And the start of chapter14 (section 14.1 to be more precise) specifies what a normal and abrupt completion is. For example a return
with a given value is an abrupt completion.
因此在这种情况下,finally
块突然完成(原因:return
具有给定值),因此 try
将突然完成出于同样的原因(并返回 3).这在 第 14.17 节关于return 声明 以及
Hence in this case, the finally
block completes abruptly (reason: return
with a given value), so the try
will complete abruptly for the same reason (and return 3). This is confirmed in section 14.17 about the return statement as well
如果表达式的计算正常完成,产生一个值 V,那么 return 语句突然完成,原因是一个返回值 V.
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.
这篇关于Java在try-catch-finally机制中的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!