Skip to content

Commit 28e7878

Browse files
committed
Java 中的 finally 是否总会执行?
1 parent a89147c commit 28e7878

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
##问题
2+
3+
有一个 try/catch 代码块,其中包含一个打印语句。finally代码块总会被执行么?
4+
5+
示例:
6+
7+
``` java
8+
try {
9+
something();
10+
return success;
11+
}
12+
catch (Exception e) {
13+
return failure;
14+
}
15+
finally {
16+
System.out.println("i don't know if this will get printed out.");
17+
}
18+
```
19+
20+
##回答
21+
22+
1. ```finally``` 将会被调用。
23+
24+
只有以下情况 ```finally``` 不会被调用:
25+
26+
- 当你使用 ```System.exit()```
27+
- 其他线程干扰了现在运行的线程(通过 ```interrupt``` 方法)
28+
- 如果 JVM 已经“撞毁”了
29+
30+
Answered by [Jodonnell](http://stackoverflow.com/users/4223/jodonnell),edited by [jpaugh](http://stackoverflow.com/users/712526/jpaugh).
31+
32+
2. //示例代码
33+
34+
``` java
35+
class Test
36+
{
37+
public static void main(String args[])
38+
{
39+
System.out.println(Test.test());
40+
}
41+
42+
public static int test()
43+
{
44+
try {
45+
return 0;
46+
}
47+
finally {
48+
System.out.println("finally trumps return.");
49+
}
50+
}
51+
}
52+
```
53+
输出:
54+
55+
``` java
56+
finally trumps return.
57+
0
58+
```
59+
60+
Answered by [Kevin](http://stackoverflow.com/users/1058366/kevin)
61+
62+
---
63+
原文链接:http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java?page=1&tab=votes#tab-top

0 commit comments

Comments
 (0)