怎么一次抛出多个异常

tech2022-12-25  66

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

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); } } }

测试结果如下:

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

最新回复(0)