通常来说,我们在捕获到系统异常的时候,更想加入自己的异常信息说明解释。之前,我都是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()来获取异常链详细信息。