Java异常链

是什么

一种面向对象的编程技术,将捕获到的异常重新封装到一个新的异常中,并重新抛出。

有什么用

可以保留每一层的异常信息,用户查看异常的时候,能够从顶层异常信息看到底层异常信息。

怎么用

catch异常之后,将异常作为参数生成一个新的异常并抛出。

/*
 * @author zongpeng qiao
 * */
public class TextChainedException {
    public static void main(String[] args) {
        try {
            //throw original exception
            throw new FileNotFoundException("oops, no file");
        } catch (Exception ex) {
            //catch exception and make it into a new exception as member param cause.
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
}

运行以上代码,会得到以下错误(Caused by 部分就是底层的异常信息)

原文地址:https://www.cnblogs.com/darrenqiao/p/9185555.html