Java异常学习三:异常链

一.异常链

  1. 常常会再捕获一个异常后跑出另外一个异常,并且希望把异常原始信息保存下来,这被称为异常链。
  2. 在JDK1.4以前,程序员必须自己编写代码来保存原始异常信息,
  3. 现在所有Throwable的子类子构造器中都可以接受一个cause对象作为参数,这个cause就异常原由,代表着原始异常,即使在当前位置创建并抛出行的异常,也可以通过这个cause追踪到异常最初发生的位置。
  4. 只有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. 1和2分别通过initCause()和构造器设置cause。
  2. 3的出发点和1 2 一样,当能否运行通过?答案是不能,参考http://zy19982004.iteye.com/admin/blogs/1974796 throwable 不能是它自己的 cause。
  3. 控制台信息
    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
     

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值