为什么打印1? [英] Why is printed 1?
问题描述
我有代码:
class Test {
public static void main(final String [] args) {
System.out.println(foo());
}
private static int foo() {
int a = 0;
try {
++a;
return a;
} finally {
a = 10;
}
}
}
我无法理解为什么要打印1.
I can't uderstand why 1 is printed.
推荐答案
try {
++a;
return a; // 1 is returned here
} finally {
a = 10; // a is assigned with 10 later.
}
a
的值递增,并在try
块本身中返回.发布此return
后,将在finally
块中重新分配a
的值.这就是为什么它打印 1 的原因.
The value of a
is incremented and returned in the try
block itself. Post this return
, the value of a
is re-assigned in the finally
block. And that is the reason, why it prints 1.
Quoting from the docs. This should help you understand it more clearly.
最终编译
try-finally语句的编译与try-catch的类似.在try语句外部进行控制转移之前,无论该转移是正常转移还是突然转移,由于引发了异常,必须首先执行finally子句.对于这个简单的示例:
Compilation of a try-finally statement is similar to that of try-catch. Prior to transferring control outside the try statement, whether that transfer is normal or abrupt, because an exception has been thrown, the finally clause must first be executed. For this simple example:
void tryFinally() {
try {
tryItOut();
} finally {
wrapItUp();
}
}
编译后的代码是:
Method void tryFinally()
0 aload_0 // Beginning of try block
1 invokevirtual #6 // Method Example.tryItOut()V
4 jsr 14 // Call finally block
7 return // End of try block
8 astore_1 // Beginning of handler for any throw
9 jsr 14 // Call finally block
12 aload_1 // Push thrown value
13 athrow // ...and rethrow value to the invoker
14 astore_2 // Beginning of finally block
15 aload_0 // Push this
16 invokevirtual #5 // Method Example.wrapItUp()V
19 ret 2 // Return from finally block
Exception table:
From To Target Type
0 4 8 any
有四种方法可以使控制传递到try语句之外:
There are four ways for control to pass outside of the try statement:
- 跌落到那个方块的底部
- 返回
- 通过执行break或Continue语句
- 通过引发异常.
这篇关于为什么打印1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!