首先說明下:網(wǎng)上大多說法(finally塊會執(zhí)行,并都會在return之前執(zhí)行)都是錯誤的。
package cn.yu.test001;
/**
*
* Created by myeclipse8.5.
* User: @author yu
* Time: 2011-4-19
* Company: 天極傳媒集團
* Descripion: 測試
*/
public class testReturn {
public static int test() {
try {
return fun1();
} catch (Exception e) {
} finally {
return fun2();
}
}
public static int fun1() {
System.out.println("fun1被執(zhí)行了");
System.out.println("fun1的確被執(zhí)行了,返回么?");
return 1;
}
public static int fun2() {
System.out.println("fun2被執(zhí)行了");
System.out.println("fun2的確被執(zhí)行了,返回么?");
return 2;
}
public static void main(String[] args) {
System.out.println(testReturn.test());
}
}
結(jié)果:fun1被執(zhí)行了
fun1的確被執(zhí)行了,返回么?
fun2被執(zhí)行了
fun2的確被執(zhí)行了,返回么?
2
證明什么?finally并沒有在之前執(zhí)行,第一個執(zhí)行的還是try里面的內(nèi)容但是沒有立刻返回,等待執(zhí)行finally,當finally返回結(jié)果后執(zhí)行完畢。
并不是網(wǎng)上大多數(shù)的說法
還有要說明下 如果finally里面沒有返回值,則返回try里面的返回值。