一.异常链
- 常常会再捕获一个异常后跑出另外一个异常,并且希望把异常原始信息保存下来,这被称为异常链。
- 在JDK1.4以前,程序员必须自己编写代码来保存原始异常信息,
- 现在所有Throwable的子类子构造器中都可以接受一个cause对象作为参数,这个cause就异常原由,代表着原始异常,即使在当前位置创建并抛出行的异常,也可以通过这个cause追踪到异常最初发生的位置。
- 只有Error,Exception,RunimeException提供了带cause参数的构造器,其他的所以异常就只有通过initCause()来设置cause了。
二.代码
package com.jyz.study.jdk.exception;
/**
* 异常链
* @author JoyoungZhang@gmail.com
*
*/
public class ExceptionCause {
public static void main(String[] args) throws Exception {
test1();
}
private static void test1() throws Exception{
try{
test2();
}catch(NullPointerException ex){
//1 Exception bussinessEx = new Exception("packag exception");
// bussinessEx.initCause(ex);
// throw bussinessEx;
//2 throw new Exception("packag exception", ex);
//3 throw (Exception)ex.fillInStackTrace().initCause(ex);
}
}
private static void test2(){
test3();
}
private static void test3(){
throw new NullPointerException("str is null");
}
}
- 1和2分别通过initCause()和构造器设置cause。
- 3的出发点和1 2 一样,当能否运行通过?答案是不能,参考http://zy19982004.iteye.com/admin/blogs/1974796 throwable 不能是它自己的 cause。
- 控制台信息
Exception in thread "main" java.lang.Exception: packag exception at com.jyz.study.jdk.exception.ExceptionCause.test1(ExceptionCause.java:18) at com.jyz.study.jdk.exception.ExceptionCause.main(ExceptionCause.java:11) Caused by: java.lang.NullPointerException: str is null at com.jyz.study.jdk.exception.ExceptionCause.test3(ExceptionCause.java:31) at com.jyz.study.jdk.exception.ExceptionCause.test2(ExceptionCause.java:27) at com.jyz.study.jdk.exception.ExceptionCause.test1(ExceptionCause.java:16) ... 1 more