1.自定义新的异常
public class DrunkException extends Exception {
public DrunkException(String message){
super(message);
}
public DrunkException(){}
}
2.测试异常链
public class ChainTest {
/**
* Test1():抛出“喝大了”异常
* Test2():调用Test1(),捕获“喝大了”异常,并且包装成运行时异常,继续抛出
* main()方法中,调用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("司机一滴酒,情人两行泪");
newExc.initCause(e);
throw newExc;
}
}
}
3.运行结果