有时候我们可以把捕获到的异常包装成一个新的异常,然后在新的异常里添加对原始异常的引用,再把新的异常抛出,
就像链式反应,一个接着另一个。这种情况就叫做异常链。
注:新的异常中包含原始异常的所有信息
例如:
public class ChainTest {
public static void main(String[] args) {
try{
test2();
}catch(Exception e){
e.printStackTrace();//将此 throwable 及其追踪输出至标准错误流。
}
}
public static void test1() throws Exception{
throw new Exception("原始异常");
}
public static void test2(){
try {
test1();
} catch (Exception e) {
//方法一
RuntimeException newExc=new RuntimeException("新的异常"); //用指定的详细消息构造一个新的运行时异常
newExc.initCause(e); //通过调用initCause()方法去调用原始异常
throw newExc; //抛出异常
//方法二(与上面的方法效果相同)
//RuntimeException newExc=new RuntimeException(e);
//throw newExc;
}
}
}
运行结果:
java.lang.RuntimeException: 新的异常
at com.exception.ChainTest.test2(ChainTest.java:17)
at com.exception.ChainTest.main(ChainTest.java:4)
Caused by: java.lang.Exception: 原始异常
at com.exception.ChainTest.test1(ChainTest.java:10)
at com.exception.ChainTest.test2(ChainTest.java:14)
... 1 more
由上述运行结果可以看出,新的异常中包含原始异常的所有信息。