在http://www.cnitblog.com/yemoo/archive/2008/06/18/45850.html文中巧用try finally;但是讓我對finally執行過程有點疑惑,發現java的try catch功能和js是一樣的。下面列出例子:
public int test1(){
int i=4;
try{ return i;}finally{ i=0;System.out.println("---test----");}
}
執行結果:輸出---test----,test1方法返回4;我的疑惑是為什么不返回0
在QQ群里討論的時候,有人說finally中的語句在try中的return后執行。但是如下代碼執行否決了上面的結論。
public int test2(){
int i=4;
try{ return i;}finally{ i=0;System.out.println("---test----");return i;}
}
注意:在finally中多了個return i;
執行結果:輸出---test----,test2方法返回0;
這個例說明了finally中的語句是在try的return執行前執行的。那么test1方法的finally中i=0了,但是為什么test1方法還返回4呢?這是我的疑惑,那位知道解釋一下。