異常鏈?zhǔn)纠a注釋
一直覺得異常是一個(gè)過不去的坎,因?yàn)橥﹄y理解的。
對(duì)著慕課網(wǎng)老師的示例,手動(dòng)敲了代碼,并一步步加上syso跟蹤,終于對(duì)異常throw/throws有更深的理解,現(xiàn)在把驗(yàn)證代碼和注釋貼上來,希望和有疑惑的同學(xué)一起交流。
package?com.imooc.season3; public?class?ThrowDemo?extends?Exception?{ //TODO:?自定義Java?Exception ,繼承Exception父類 public?ThrowDemo(){?//construtor函數(shù)構(gòu)造器,無參 } public?ThrowDemo(String?s){ super(s); System.out.println("Here?is?ThrowDemo(String?s)"); } }
package?com.imooc.season3; public?class?ThrowDemoTest?{ public?void?test01()?throws?ThrowDemo{?//throws?declaration聲明該方法有異常拋出 System.out.println("step02:Reach?test01,new?ThrowDemo?初始化函數(shù)構(gòu)造器--》ThrowDemo異常對(duì)象,并拋出throw?e"); throw?new?ThrowDemo("test01拋出異常");??//throw?拋出異常的動(dòng)作 } public?void?test02(){ try?{ System.out.println("step01:準(zhǔn)備運(yùn)行test01"); test01(); }?catch?(ThrowDemo?e)?{???//方法test01中會(huì)拋出異常,因此調(diào)用該方法的時(shí)候就try?catch它預(yù)料中的異常 //e.printStackTrace();??????????//ThrowDemo?e?=?new?ThrowDemo(s),初始化自定義異常,追溯并打印本類中該異常的錯(cuò)誤源頭 //System.out.println(); System.out.println("step03:接收test01中的拋出throw,匹配是ThrowDemo對(duì)象,到達(dá)test02?Catch?塊"); RuntimeException?excption01?=?new?RuntimeException("test02中runtimeException中的catch塊"); excption01.initCause(e);??//initCause(?throwable?cause)?即參數(shù)為可拋出異常的對(duì)象,ThrowDemo?e繼承Exception父類,即也屬于throwable類 //如果沒有.initCause(?throwable?cause),即沒有定義causeby源頭異常/起始異常---異常鏈,printStackTrace的時(shí)候就不能打印cause?by throw?excption01;?//拋出異常exception01?? } } public?static?void?main(String[]?args)?{ /* ?*??TODO?? ?*??test01拋出異常 ?*??test02調(diào)用有拋出異常的方法,對(duì)該方法進(jìn)行try異常捕獲catch,并且包裝成運(yùn)行時(shí)異常,繼續(xù)拋出 ?*??main方法,調(diào)用test02方法,嘗試捕獲test02的異常 ?*/ ThrowDemoTest?t01=new?ThrowDemoTest(); try{t01.test02(); }catch(Exception?e){ System.out.println("step04:到達(dá)main?Catch?塊,catch接收throw出來的excption01"); e.printStackTrace(); } } }
結(jié)果result:
step01:準(zhǔn)備運(yùn)行test01
step02:Reach test01,new ThrowDemo 初始化函數(shù)構(gòu)造器--》ThrowDemo異常對(duì)象,并拋出throw e
Here is ThrowDemo(String s)
step03:接收test01中的拋出throw,匹配是ThrowDemo對(duì)象,到達(dá)test02 Catch 塊
step04:到達(dá)main Catch 塊,catch接收throw出來的excption01
java.lang.RuntimeException: test02中runtimeException中的catch塊
at com.imooc.season3.ThrowDemoTest.test02(ThrowDemoTest.java:18)
at com.imooc.season3.ThrowDemoTest.main(ThrowDemoTest.java:32)
Caused by: com.imooc.season3.ThrowDemo: test01拋出異常
at com.imooc.season3.ThrowDemoTest.test01(ThrowDemoTest.java:7)
at com.imooc.season3.ThrowDemoTest.test02(ThrowDemoTest.java:13)
... 1 more
2016-08-01
并不能看懂,邏輯不是很清楚
2016-02-05
異常在哪里?
2016-01-03
謝謝啦