对应的自定义异常类为:
上述代码输出结果为:
throwException
com.lwf.thinking.eight.EusException
at com.lwf.thinking.eight.UserDefineException.catchException(UserDefineException.java:19)
at com.lwf.thinking.eight.UserDefineException.main(UserDefineException.java:9)
可以看到输出结果看不到最开始的throwException中抛出的SQLException,这是因为在catchException中抛出的是EusException而不是SQLException
那么当我抛出另一个异常的时候也想让这个异常包含引发它的异常怎么做呢?
修改异常类:增加方法
public EusException(Throwable cause){
super(cause);
}
对应异常类为:
代码改为:
throw new EusException(e);
如下:
输出结果为:
throwException
com.lwf.thinking.eight.EusException: java.sql.SQLException
at com.lwf.thinking.eight.UserDefineException.catchException(UserDefineException.java:19)
at com.lwf.thinking.eight.UserDefineException.main(UserDefineException.java:9)
Caused by: java.sql.SQLException
at com.lwf.thinking.eight.UserDefineException.throwException(UserDefineException.java:25)
at com.lwf.thinking.eight.UserDefineException.catchException(UserDefineException.java:17)
... 1 more
可以看到结果列出了引发的原始异常SQLException。
注意,因为JAVA API中有很多类并没有参数为Throwable 类型的构造函数:
public EusException(Throwable cause){
super(cause);
}
但自Throwable类继承过来的类都有initCause(Throwable cause)方法,所以另一种实现的方式是:
异常类不变。