Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d0072e0

Browse files
committed
Merge pull request giantray#17 from nitta-honoka/master
Java 中的 finally 是否总会执行?
2 parents a89147c + c4fe3c9 commit d0072e0

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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+
只有以下情况 ```finally``` 不会被调用:
24+
25+
- 当你使用 ```System.exit()```
26+
- 其他线程干扰了现在运行的线程(通过 ```interrupt``` 方法)
27+
- 如果 JVM 已经"撞毁"了
28+
29+
Answered by [Jodonnell](http://stackoverflow.com/users/4223/jodonnell), edited by [jpaugh](http://stackoverflow.com/users/712526/jpaugh).
30+
31+
2. //示例代码
32+
33+
``` java
34+
class Test
35+
{
36+
public static void main(String args[])
37+
{
38+
System.out.println(Test.test());
39+
}
40+
41+
public static int test()
42+
{
43+
try {
44+
return 0;
45+
}
46+
finally {
47+
System.out.println("finally trumps return.");
48+
}
49+
}
50+
}
51+
```
52+
输出:
53+
54+
``` java
55+
finally trumps return.
56+
0
57+
```
58+
Answered by [Kevin](http://stackoverflow.com/users/1058366/kevin)
59+
60+
---
61+
原文链接:http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java?page=1&tab=votes#tab-top

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /