2010-07-30 73 views
13

在.net中,AggregateException类允许您引发包含多个异常的异常。什么是来自.net的AggregateException的Java等价物?

例如,如果您并行运行多个任务,并且其中一些任务因异常而失败,您将希望抛出一个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); 
} 
+0

,我不知道一个内置。但是,我从来没有找过一个。 – Powerlord 2010-07-30 20:08:08

回答

3

我不知道任何内置或库类,因为我从来没有想过要这样做(通常你只是链接例外),但它不会很难写下自己。

你可能想选择一个例外是“主”,因此它可以用来填补踪迹,等

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

} 
0

我真的不明白为什么你应该使用异常摆在首位,以纪念任务未完成/失败,但在任何情况下,不该自己创造一个很难。得到任何代码分享,以便我们可以帮助你更具体的答案?

+0

我不是用它来“标记”任何东西,我只是想表明至少有一次失败。我编辑了主帖以包含代码。 – 2010-07-30 20:16:24

+0

这个例子有用的一个例子是验证。不是在第一个无效属性上抛出异常,而是验证整个类,以便消费者可以理解有效载荷无效的原因。这是发现API的更好方法。 – Brandon 2015-02-05 17:26:45

1

可以代表多个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(如果存在的话)就是在其相关任务中抛出的任何异常。

+0

很高兴看到已有方法可以同时运行任务。但是,您的解决方案并不涉及抛出表示多个任务失败的异常。 – 2010-07-31 18:08:29

相关问题