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