1 引子
try…catch…finally恐怕是大家再熟悉不過的語句了,而且感覺用起來也是很簡單,邏輯上似乎也是很容易理解。不過,我親自體驗的“教訓”告訴我,這個東西可不是想象中的那麼簡單、聽話。不信?那你看看下面的代碼,“猜猜”它執行後的結果會是什麼?不要往後看答案、也不許執行代碼看真正答案哦。如果你的答案是正確,那麼這篇文章你就不用浪費時間看啦。
package myExample.testException;
public class TestException {
public TestException() {
}
boolean testEx() throws Exception{
boolean ret = true;
try{
ret = testEx1();
}catch (Exception e){
System.out.println("testEx, catch exception");
ret = false;
throw e;
}finally{
System.out.println("testEx, finally; return value="+ret);
return ret;
}
}
boolean testEx1() throws Exception{
boolean ret = true;
try{
ret = testEx2();
if (!ret){
return false;
}
System.out.println("testEx1, at the end of try");
return ret;
}catch (Exception e){