先创建一个自定义异常类:
package demo;
public class demoException extends Exception {//自定义异常类继承于Exception类
public demoException() {
}
public demoException(String me) { //有参构造方法
super(me);//调用父类构造方法并传参数进去
}
}
具体异常链代码示例:
我自己都没看懂,emmm
package demo;
import java.util.concurrent.ExecutionException;
public class ChainTest {
/*
* test1():抛出“自定义”异常 test2():调用test1(),捕获“自定义”异常,并且包装成运行时异常继续抛出
* main方法中,调用test2(),尝试捕获test2()方法抛出的异常
*/
public static void main(String[] args) {
ChainTest ct = new ChainTest(); // 创建对象
try{
ct.test2();//CT类对象调用test2方法产生异常
}
catch (Exception e) {//捕获异常到Exc..类的对象e中
e.printStackTrace();//包含错误信息的对象e调用pST方法打印异常信息
}
}
public void test1() throws demoException {// 必须要声明抛出的异常类型
throw new demoException("喝酒");// 新建一个自定义异常类对象并传入参数然后抛出。
}
public void test2() {
try {
test1();// 调用的方法有异常,需要用try{}Catch{}处理
} catch (demoException q) {// 新建一个自定义异常类对象 q,并将异常信息包含进去,{}内为具体处理异常方法
RuntimeException newExc = new RuntimeException("撞车");// 新建Run..(运行时)异常对象,并往构造器传参
newExc.initCause(q);// 使用Runtime..类对象调用iniCause方法将异常信息传递到上层
throw newExc;// 将newExc抛出
}
}
}
java.lang.RuntimeException:撞车
在demo.ChainTest.test2(ChainTest.java:31)
在demo.ChainTest.main(ChainTest.java:13)
引起:demo.demoException:喝酒
在demo.ChainTest.test1(ChainTest.java:23)
在demo.ChainTest.test2(ChainTest.java:28)
... 1更多
根据运行结果来看,ChainTest对象调用有异常的test2(),但是test2()调用了test1(),test1()也有异常且test1()异常是根本原因。