思維有些混亂,能否用俗語解釋下這篇代碼
public class ChainTest {
public static void main(String[] args) {
ChainTest ct=new ChainTest();
try{
ct.test2();
}catch(Exception e){
e.printStackTrace();
}
}
public void test1() throws DrunkException{
throw new DrunkException("開車別喝酒");
}
public void test2(){
try {
test1();
} catch (DrunkException e) {
// TODO Auto-generated catch block
RuntimeException newExc=new RuntimeException(e);
//newExc.initCause(e);
throw newExc;
}
}
}
2017-05-02
test1是拋出一個異常,test2是接收test1的異常并輸出運行異常。
2017-05-02
public?class?ChainTest?{//先看test1的注釋,再看test2的,再看main函數 public?static?void?main(String[]?args)?{? ChainTest?ct=new?ChainTest(); try{ ct.test2();//test2丟出了這個異常,所以由父類捕捉 }catch(Exception?e){ e.printStackTrace(); } } public?void?test1()?throws?DrunkException{//test1我們手動拋出了一個異常,由于使用了throws?DrunkException,就給父類捕捉這個異常 throw?new?DrunkException("開車別喝酒"); } public?void?test2(){ try?{ test1();//調用了test1,test1我們手動拋出了一個異常,所以由test2這個父類來捕獲這個異常。還有test2應該也要使用throws?DrunkException?吧 }?catch?(DrunkException?e)?{ //?TODO?Auto-generated?catch?block RuntimeException?newExc=new?RuntimeException(e); //newExc.initCause(e); throw?newExc; } } }