.net的AggregateException的java等价物是什么?
发布时间:2020-11-18 12:26:37 所属栏目:Java 来源:互联网
导读:在.net中,AggregateException类允许您抛出包含多个异常的异常. 例如,如果并行运行多个任务,那么您将要抛出一个AggregateException,其中一些任务失败,例外. java有相当的类吗? 具体情况我想用它在: public static void runMultipleThenJoin(Runnable... jobs
在.net中,AggregateException类允许您抛出包含多个异常的异常. 例如,如果并行运行多个任务,那么您将要抛出一个AggregateException,其中一些任务失败,例外. java有相当的类吗? 具体情况我想用它在: public static void runMultipleThenJoin(Runnable... jobs) { final List<Exception> errors = new Vector<Exception>(); try { //create exception-handling thread jobs for each job List<Thread> threads = new ArrayList<Thread>(); for (final Runnable job : jobs) threads.add(new Thread(new Runnable() {public void run() { try { job.run(); } catch (Exception ex) { errors.add(ex); } }})); //start all for (Thread t : threads) t.start(); //join all for (Thread t : threads) t.join(); } catch (InterruptedException ex) { //no way to recover from this situation throw new RuntimeException(ex); } if (errors.size() > 0) throw new AggregateException(errors); } 解决方法我不知道任何内置或图书馆类,因为我从来没有想要这样做(通常你只是链接异常),但写自己并不难.您可能希望选择其中一个例外作为“主要”,因此可用于填充堆栈跟踪等. public class AggregateException extends Exception { private final Exception[] secondaryExceptions; public AggregateException(String message,Exception primary,Exception... others) { super(message,primary); this.secondaryExceptions = others == null ? new Exception[0] : others; } public Throwable[] getAllExceptions() { int start = 0; int size = secondaryExceptions.length; final Throwable primary = getCause(); if (primary != null) { start = 1; size++; } Throwable[] all = new Exception[size]; if (primary != null) { all[0] = primary; } Arrays.fill(all,start,all.length,secondaryExceptions); return all; } } (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |