1.自定義新的異常
public class DrunkException extends Exception {
public DrunkException(String message){
super(message);
}
public DrunkException(){}
}
2.測(cè)試異常鏈
public class ChainTest {
/**
* Test1():拋出“喝大了”異常
* Test2():調(diào)用Test1(),捕獲“喝大了”異常,并且包裝成運(yùn)行時(shí)異常援雇,繼續(xù)拋出
* main()方法中匆帚,調(diào)用test2(),嘗試捕獲test2()方法拋出的異常
* */
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){
RuntimeException newExc=new RuntimeException("司機(jī)一滴酒轮听,情人兩行淚");
newExc.initCause(e);
throw newExc;
}
}
}
3.運(yùn)行結(jié)果