1.try和catch中有return时,finally先执行
1 public class tryDemo {
2 public static int show() {
3 try {
4 return 1;
5 }finally{
6 System.out.println("finally模块被执行");
7 }
8 }
9 public static void main(String args[]) {
10 System.out.println(show());
11 }
12 }
13 ----------
14 finally模块被执行
15 1
public class tryDemo {
public static int show() {
try {
int a = 8/0;
return 1;
}catch (Exception e) {
return 2;
}finally{
System.out.println("finally模块被执行");
}
}
public static void main(String args[]) {
System.out.println(show());
}
}
------------
finally模块被执行
2
2.如果finally也有return,直接return
1 public class tryDemo {
2 public static int show() {
3 try {
4 int a = 8/0;
5 return 1;
6 }catch (Exception e) {
7 return 2;
8 }finally{
9 System.out.println("finally模块被执行");
10 return 0;
11 }
12 }
13 public static void main(String args[]) {
14 System.out.println(show());
15 }
16 }
17 -------------
18 finally模块被执行
19 0
3.finally中对于返回变量做的改变->会影响最终的返回结果
1 public class Test {
2 public Object show1() {
3 Peo obj = new Peo();
4 obj.setName("1");
5 try {
6 System.out.println(obj);
7 return obj;
8 } finally {
9 System.out.println("finally模块被执行");
10 obj.setName("2");
11 }
12 }
13
14 public Object show2() {
15 Peo obj = new Peo();
16 obj.setName("1");
17 try {
18 System.out.println(obj);
19 return obj;
20 } finally {
21 System.out.println("finally模块被执行");
22 obj = null;
23 }
24 }
25
26 public Object show3() {
27 Peo obj = new Peo();
28 obj.setName("1");
29 try {
30 System.out.println(obj);
31 return obj;
32 } finally {
33 System.out.println("finally模块被执行");
34 obj = null;
35 return obj;
36 }
37 }
38
39 public static void main(String args[]) {
40 Test test = new Test();
41 System.out.println(test.show1());
42 System.out.println("*************");
43 System.out.println(test.show2());
44 System.out.println("*************");
45 System.out.println(test.show3());
46 }
47
48 class Peo {
49 String name;
50
51 public void setName(String name) {
52 this.name = name;
53 }
54
55 @Override
56 public String toString() {
57 return "Peo [name=" + name + "]";
58 }
59 }
60 }
61 --------------------
62 Peo [name=1]
63 finally模块被执行
64 Peo [name=2]
65 *************
66 Peo [name=1]
67 finally模块被执行
68 Peo [name=1]
69 *************
70 Peo [name=1]
71 finally模块被执行
72 null