try {}里有一個(gè)return語(yǔ)句,那么緊跟在這個(gè)try后的finally {}里的code會(huì)不會(huì)被執(zhí)行,什么時(shí)候被執(zhí)行,在return前還是后?
public class test { public static void main(String[] args) { System.out.println(new test().test());; }
static int test() { int x = 1; try { return x; } finally { ++x; System.out.println(x); System.out.println("aaa"); } } }
運(yùn)行結(jié)果是
2
aaa
1
為什么呢?主函數(shù)調(diào)用子函數(shù)并得到結(jié)果的過(guò)程,好比主函數(shù)準(zhǔn)備一個(gè)空罐子,當(dāng)子函數(shù)要返回結(jié)果時(shí),先把結(jié)果放在罐子里,然后再將程序邏輯返回到主函數(shù)。
所謂返回,就是子函數(shù)說(shuō),我不運(yùn)行了,你主函數(shù)繼續(xù)運(yùn)行吧,這沒(méi)什么結(jié)果可言,結(jié)果是在說(shuō)這話之前放進(jìn)罐子里的。
public class smallT
{
public static void main(String args[])
{
smallT t = new smallT();
int b = t.get();
System.out.println(b);
}
public int get()
{
try
{
return 1 ;
}
finally
{
return 2 ;
}
}
}
返回的結(jié)果是2。
我可以通過(guò)下面一個(gè)例子程序來(lái)幫助我解釋這個(gè)答案,從下面例子的運(yùn)行結(jié)果中可以發(fā)現(xiàn),try中的return語(yǔ)句調(diào)用的函數(shù)先于finally中調(diào)用的函數(shù)執(zhí)行,
也就是說(shuō)return語(yǔ)句先執(zhí)行,finally語(yǔ)句后執(zhí)行,所以,返回的結(jié)果是2。Return并不是讓函數(shù)馬上返回,而是return語(yǔ)句執(zhí)行后,將把返回結(jié)果放置進(jìn)函數(shù)棧中,
此時(shí)函數(shù)并不是馬上返回,它要執(zhí)行finally語(yǔ)句后才真正開(kāi)始返回。
在講解答案時(shí)可以用下面的程序來(lái)幫助分析:
public class Test {
/**
* @param args add by zxx ,Dec 9, 2008
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new Test().test());;
}
int test(){
try
{
return func1();
}
finally
{
return func2();
}
}
int func1()
{
System.out.println("func1");
return 1;
}
int func2()
{
System.out.println("func2");
return 2;
}
}
-----------執(zhí)行結(jié)果-----------------
func1
func2
2結(jié)論:finally中的代碼比return 和break語(yǔ)句后執(zhí)行
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。