File tree 1 file changed +61
-0
lines changed
1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments