亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

異常鏈示例代碼注釋

一直覺得異常是一個過不去的坎,因為挺難理解的。

對著慕課網老師的示例,手動敲了代碼,并一步步加上syso跟蹤,終于對異常throw/throws有更深的理解,現在把驗證代碼和注釋貼上來,希望和有疑惑的同學一起交流。

package?com.imooc.season3;

public?class?ThrowDemo?extends?Exception?{

			//TODO:?自定義Java?Exception	,繼承Exception父類
	
	public?ThrowDemo(){?//construtor函數構造器,無參
		
	}
	
	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?初始化函數構造器--》ThrowDemo異常對象,并拋出throw?e");
		throw?new?ThrowDemo("test01拋出異常");??//throw?拋出異常的動作
	}
	
	public?void?test02(){
		try?{
			System.out.println("step01:準備運行test01");
			test01();
		}?catch?(ThrowDemo?e)?{???//方法test01中會拋出異常,因此調用該方法的時候就try?catch它預料中的異常
			//e.printStackTrace();??????????//ThrowDemo?e?=?new?ThrowDemo(s),初始化自定義異常,追溯并打印本類中該異常的錯誤源頭
			//System.out.println();
			System.out.println("step03:接收test01中的拋出throw,匹配是ThrowDemo對象,到達test02?Catch?塊");
			RuntimeException?excption01?=?new?RuntimeException("test02中runtimeException中的catch塊");
			excption01.initCause(e);??//initCause(?throwable?cause)?即參數為可拋出異常的對象,ThrowDemo?e繼承Exception父類,即也屬于throwable類
			//如果沒有.initCause(?throwable?cause),即沒有定義causeby源頭異常/起始異常---異常鏈,printStackTrace的時候就不能打印cause?by
			throw?excption01;?//拋出異常exception01??
		}
	}
	public?static?void?main(String[]?args)?{
		/*
		?*??TODO??
		?*??test01拋出異常
		?*??test02調用有拋出異常的方法,對該方法進行try異常捕獲catch,并且包裝成運行時異常,繼續拋出
		?*??main方法,調用test02方法,嘗試捕獲test02的異常
		?*/
		ThrowDemoTest?t01=new?ThrowDemoTest();
		try{t01.test02();
		}catch(Exception?e){
			System.out.println("step04:到達main?Catch?塊,catch接收throw出來的excption01");
			e.printStackTrace();
		}
		
		
		
	}

}

結果result:

step01:準備運行test01

step02:Reach test01,new ThrowDemo 初始化函數構造器--》ThrowDemo異常對象,并拋出throw e

Here is ThrowDemo(String s)

step03:接收test01中的拋出throw,匹配是ThrowDemo對象,到達test02 Catch 塊

step04:到達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


正在回答

3 回答

并不能看懂,邏輯不是很清楚

0 回復 有任何疑惑可以回復我~

異常在哪里?

0 回復 有任何疑惑可以回復我~

謝謝啦


1 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
Java入門第三季
  • 參與學習       409767    人
  • 解答問題       4543    個

Java中你必須懂得常用技能,不容錯過的精彩,快來加入吧

進入課程

異常鏈示例代碼注釋

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號