异常链

一.异常链

  1. 常常会再捕获一个异常后跑出另外一个异常,并且希望把异常原始信息保存下来,这被称为异常链。
  2. 在JDK1.4以前,程序员必须自己编写代码来保存原始异常信息,
  3. 现在所有Throwable的子类子构造器中都可以接受一个cause对象作为参数,这个cause就异常原由,代表着原始异常,即使在当前位置创建并抛出行的异常,也可以通过这个cause追踪到异常最初发生的位置。
  4. 只有Error,Exception,RunimeException提供了带cause参数的构造器,其他的所以异常就只有通过initCause()来设置cause了。

二.代码

Java代码   收藏代码
  1. package com.jyz.study.jdk.exception;  
  2.   
  3.   
  4. /** 
  5.  * 异常链 
  6.  * @author JoyoungZhang@gmail.com 
  7.  * 
  8.  */  
  9. public class ExceptionCause {  
  10.     public static void main(String[] args) throws Exception {  
  11.     test1();  
  12.     }  
  13.   
  14.     private static void test1() throws Exception{  
  15.     try{  
  16.         test2();  
  17.     }catch(NullPointerException ex){  
  18. //1     Exception bussinessEx = new Exception("packag exception");  
  19. //      bussinessEx.initCause(ex);  
  20. //      throw bussinessEx;  
  21. //2     throw new Exception("packag exception", ex);  
  22. //3     throw (Exception)ex.fillInStackTrace().initCause(ex);  
  23.     }  
  24.     }  
  25.       
  26.     private static void test2(){  
  27.     test3();  
  28.     }  
  29.       
  30.     private static void test3(){  
  31.     throw new  NullPointerException("str is null");  
  32.     }  
  33.   
  34. }  

 

 

  1. 1和2分别通过initCause()和构造器设置cause。
  2. 3的出发点和1 2 一样,当能否运行通过?答案是不能,参考http://zy19982004.iteye.com/admin/blogs/1974796 throwable 不能是它自己的 cause。
  3. 控制台信息
    Java代码   收藏代码
    1. Exception in thread "main" java.lang.Exception: packag exception  
    2.     at com.jyz.study.jdk.exception.ExceptionCause.test1(ExceptionCause.java:18)  
    3.     at com.jyz.study.jdk.exception.ExceptionCause.main(ExceptionCause.java:11)  
    4. Caused by: java.lang.NullPointerException: str is null  
    5.     at com.jyz.study.jdk.exception.ExceptionCause.test3(ExceptionCause.java:31)  
    6.     at com.jyz.study.jdk.exception.ExceptionCause.test2(ExceptionCause.java:27)  
    7.     at com.jyz.study.jdk.exception.ExceptionCause.test1(ExceptionCause.java:16)  
    8.     ... 1 more  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值