網(wǎng)上看到這段代碼,沒(méi)有像課里講的一樣產(chǎn)生異常鏈?
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)?{??
????????????System.out.println("testEx1,?catch?exception");??
????????????ret?=?false;??
????????????throw?e;??
????????}?finally?{??
????????????System.out.println("testEx1,?finally;?return?value="?+?ret);??
????????????return?ret;??
????????}??
????}??
??
????boolean?testEx2()?throws?Exception?{??
????????boolean?ret?=?true;??
????????try?{??
????????????int?b?=?12;??
????????????int?c;??
????????????for?(int?i?=?2;?i?>=?-2;?i--)?{??
????????????????c?=?b?/?i;??
????????????????System.out.println("i="?+?i);??
????????????}??
????????????return?true;??
????????}?catch?(Exception?e)?{??
????????????System.out.println("testEx2,?catch?exception");??
????????????ret?=?false;??
????????????throw?e;??
????????}?finally?{??
????????????System.out.println("testEx2,?finally;?return?value="?+?ret);??
????????????return?ret;??
????????}??
????}??
??
????public?static?void?main(String[]?args)?{??
????????TestException?testException1?=?new?TestException();??
????????try?{??
????????????testException1.testEx();??
????????}?catch?(Exception?e)?{??
????????????e.printStackTrace();??
????????}??
????}??
} ?
代碼輸出結(jié)果是:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
?不明白的是為什么testEx1和testEx都沒(méi)有捕獲到異常。
2016-04-08
你throw了一個(gè)異常,然后finally中又返回了一個(gè)值,相當(dāng)于方法正常結(jié)束,所以異常就沒(méi)了。finally中不要加return。
2016-07-14
boolean?ret?=?true;??
????????try?{??
????????????ret?=?testEx2();??
????????????if?(!ret)?{??
????????????????return?false;??
????????????}??
????????????System.out.println("testEx1,?at?the?end?of?try");??
????????????return?ret; ?
這段代碼的意思是定義ret為真,如果testEx2(); 返回值為假,則拋出異常
2016-06-01
這個(gè)程序的輸出順序是先testEx2,再testEx,最后testEx。而為什么視頻上程序的輸出順序是先test2,再text1?和什么有關(guān)