Java 基础 Exception异常类的包装技术

通常来说,我们在捕获到系统异常的时候,更想加入自己的异常信息说明解释。之前,我都是throw一个Throwale的子类,这样也可以达到目标, 但是当及要求有自己定义的异常解释又要系统的异常细节原因,怎么办呢?

下面介绍一种Java SE 1.4 已经存在的方法:

java.lang.Throwable
public Throwable initCause(Throwable cause)
Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.)
This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. If this throwable was created with Throwable(Throwable) or Throwable(String, Throwable), this method cannot be called even once.
An example of using this method on a legacy throwable type without other support for setting the cause is:
       try {
           lowLevelOp();
       } catch (LowLevelException le) {
           throw (HighLevelException)
                 new HighLevelException().initCause(le); // Legacy constructor
       }
       
Parameters:
cause - the cause (which is saved for later retrieval by the getCause() method). (A null value is permitted, and indicates that the cause is nonexistent or unknown.)
Returns:
a reference to this Throwable instance.
Throws:
IllegalArgumentException - if cause is this throwable. (A throwable cannot be its own cause.)
IllegalStateException - if this throwable was created with Throwable(Throwable) or Throwable(String, Throwable), or this method has already been called on this throwable.
Since:
1.4

try{

//read files 

}catch(IOException ex){

Throwable se = new Throwable("read file error xxx")

se.initCause(se);

throw se;

}

当捕获到异常的时候,就可以使用 se.getCasue()来获取异常链详细信息。 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值