[英]What is the java equivalent of AggregateException from .net?
在.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);
}
Java 7的Throwable.addSuppressed(Throwable)会做类似的事情,虽然它的目的略有不同( try-with-resource )
我不知道任何内置或库类,因为我以前从来没有想要这样做(通常你只是链接异常),但是写自己并不难。
您可能希望选择其中一个例外为“主要”,以便可以用它来填充堆栈跟踪等。
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;
}
}
您可以将多个taska表示为
List<Callable<T>> tasks
然后,如果您希望计算机实际并行使用它们
ExecutorService executorService = .. initialize executor Service
List<Future<T>> results = executorService.invokeAll ( ) ;
现在您可以遍历结果。
try
{
T val = result . get ( ) ;
}
catch ( InterruptedException cause )
{
// this is not the exception you are looking for
}
catch ( ExecutionExeception cause )
{
Throwable realCause = cause . getCause ( ) // this is the exception you are looking for
}
因此,realCause(如果存在)是其关联任务中抛出的异常。
我真的不明白为什么你应该首先使用异常将任务标记为不完整/失败,但无论如何,自己创建一个并不困难。 有任何代码可以分享,以便我们可以帮助您找到更具体的答案吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.