怎么一次抛出多个异常

定义一个自定义异常,如下:

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义异常
 */
public class MyException extends Exception {
    /**
     * 定义一个集合容纳异常
     */
    private List<Exception> exceptions = new ArrayList<>();

    public MyException(String message, List<Exception> exceptions) {
        super(message);
        this.exceptions = exceptions;
    }

    /**
     * 获取异常信息
     *
     * @return
     */
    public List<Exception> getExceptions() {
        return exceptions;
    }
}

测试demo:

import java.util.ArrayList;
import java.util.List;

public class ThrowMoreException {
    /**
     * 假设是个注册的方法,入参就先省略了
     *
     * @return
     */
    public boolean reg() throws MyException {
        List<Exception> exceptions = new ArrayList<>();
        try {
            //假设调用业务会出现的异常
            throw new Exception("密码不能为空");
        } catch (Exception e) {
            exceptions.add(e);
        }

        try {
            //假设调用业务会出现的异常
            throw new Exception("用户名不能重复");
        } catch (Exception e) {
            exceptions.add(e);
        }

        try {
            //假设调用业务会出现的异常
            throw new Exception("邮箱非法");
        } catch (Exception e) {
            exceptions.add(e);
        }
        //如果确实有异常,那么就要抛出
        if (exceptions.size() > 0) {
            throw new MyException("注册异常", exceptions);
        }
        return true;
    }

    public static void main(String[] args) {
        try {
            new ThrowMoreException().reg();
        } catch (MyException e) {
            e.getExceptions().stream().forEach(System.out::println);
        }
    }
}

测试结果如下:
在这里插入图片描述

这样通过自定义一个异常类来容纳多个异常,间接的实现一次抛出多个异常的逻辑。

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/108380025
今日推荐