查詢了很多解釋,但網(wǎng)上都是轉(zhuǎn)載別人的,好像也沒有深究細(xì)節(jié)問題。

代碼如下:
 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被執(zhí)行了");
11         return 1;
12     }
13     public static int fun2() {
14         System.out.println("fun2被執(zhí)行了");
15         return 2;
16     }
17     public static void main(String[] args) {
18         System.out.println(new test002().test());
19     }
20 }
執(zhí)行結(jié)果:
fun1被執(zhí)行了
fun2被執(zhí)行了
2
代碼反映的情況是return首先被執(zhí)行,finally后被執(zhí)行,return并不是讓結(jié)果馬上返回,而是先把結(jié)果放到函數(shù)中,然后必須等待finally結(jié)果出來后在真正的返回,此時返回的結(jié)果就是finally當(dāng)中的那個結(jié)果