查詢了很多解釋,但網上都是轉載別人的,好像也沒有深究細節問題。
代碼如下:
代碼如下:
1 public class test002 {
2 public static int test() {
3 try {
4 return fun1();
5 } finally {
6 return fun2();
7 }
8 }
9 public static int fun1() {
10 System.out.println("fun1被執行了");
11 return 1;
12 }
13 public static int fun2() {
14 System.out.println("fun2被執行了");
15 return 2;
16 }
17 public static void main(String[] args) {
18 System.out.println(new test002().test());
19 }
20 }
執行結果:2 public static int test() {
3 try {
4 return fun1();
5 } finally {
6 return fun2();
7 }
8 }
9 public static int fun1() {
10 System.out.println("fun1被執行了");
11 return 1;
12 }
13 public static int fun2() {
14 System.out.println("fun2被執行了");
15 return 2;
16 }
17 public static void main(String[] args) {
18 System.out.println(new test002().test());
19 }
20 }
fun1被執行了
fun2被執行了
2
代碼反映的情況是return首先被執行,finally后被執行,return并不是讓結果馬上返回,而是先把結果放到函數中,然后必須等待finally結果出來后在真正的返回,此時返回的結果就是finally當中的那個結果fun2被執行了
2