JAVA基础--异常的包装技术

适用场景:

1、在写一个项目时,越往底层,其抛出的异常越多,父类需要处理这些异常,如果要将每个异常都进行catch捕获太麻烦而且还的考虑异常类子父关系的问题,当然我们也可以直接捕获它们的超类IOException。我们可以自己创建一个异常类,将底层的异常进行封装,统一抛出新建的异常类,在捕获时只捕获该异常即可,也会输出所有的错误信息。
2、如果在一个方法中发生了一个检查型异常(就是编译期异常),但这个方法不允许抛出检查型异常,那么包装技术也很有用。我们可以捕获这个检查型异常,并将它包装成一个运行时异常。
3、改变异常的抛出类型。

模拟场景1,从底层向上层抛出封装后的异常
先自定义个异常类,继承了编译期异常的超类IOException,重写initCause和getCause只是为了打印下两句话证明确实进行了封装,实际完全不需要重写。

public class ServletException extends IOException {
    
    
    public ServletException() {
    
    
    }

    public ServletException(String message) {
    
    
        super(message);
    }

    @Override
    public synchronized Throwable initCause(Throwable cause) {
    
    
        System.out.println("重新初始化了异常");
        return super.initCause(cause);
    }

    @Override
    public synchronized Throwable getCause() {
    
    
        System.out.println("输出初始化异常");
        return super.getCause();
    }
}

模拟底层抛异常并使用initCause进行初始化异常
ServletException异常对FileNotFoundException进行了封装,并将该异常抛出。

public static void test() throws ServletException{
    
    
        int arr[] = new int[]{
    
    1,3,4};
        if (arr[0] == 1) {
    
    
            FileNotFoundException e = new FileNotFoundException("e1异常");
            ServletException se = new ServletException("se异常");
            se.initCause(e);
            throw se;
        }
    }

方法调用者,即该层的上一层进行异常处理

public static void main(String[] args) {
    
    
        try {
    
    
            test();
        } catch (IOException se) {
    
    
            se.printStackTrace();
        }
    }

在这里插入图片描述
如上结果可以看出,对异常进行了封装,同时打印了异常信息,getCause知识对异常进行判断,所有方法都调用 getCause 方法来确定 throwable 的 cause。

场景2场景3也一样,可以改变自定义异常的继承类型从而改变异常类型然后封装,根据自己的选择是运行期异常还是编译期异常。

感谢这位博客的博主:
Java中关于initcause的用法说明

猜你喜欢

转载自blog.csdn.net/qq_44660367/article/details/108938268