Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine a list of exceptions?

Is there any way I can combine a list of throwables? I have a list of ListenableFutures, each of which will capture exception (if any) and keep it in a Result instance. Finally, I want to throw an exception if any of the Result of the ListenableFutures contains a throwable. The issue is how to combine multiple throwables, because there could be multiple futures that fail?

List<ListenableFuture<Result>> futureList = new ArrayList<>();
futureList.add(future1);
futureList.add(future2);
futureList.add(future3);

ListenableFuture<List<Result>> future = futureFutures.successfulAsList(futureList);

return Futures.transform(future, new Function<List<Result>, FinalResult>() {
      @Override
      public FinalResult apply(List<Result> resultList) {
        List<Throwable> throwableList = new ArrayList<>();
        for (Result result : resultList) {
            if (result.getThrowable() != null) {
                throwableList.add(result.getThowable());
            }
        }

        if (!throwableList.isEmpty()) {
           // Is there something like below that I can combine a list
           // of throwables and throw it?
           Throwable.propagateList(throwableList); // ?????????
        }
        .....
        return finalResult;
      }
    },
    MoreExecutors.sameThreadExecutor());
like image 447
Kai Avatar asked Apr 07 '16 21:04

Kai


People also ask

How do I combine two exceptions in java?

Java Catch Multiple Exceptions A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. So, if you have to perform different tasks at the occurrence of different exceptions, use java multi-catch block.

How do you handle multiple exceptions?

By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

How can I add two exceptions in one catch?

Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.

Can you throw multiple exceptions in one throw statement?

You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... } catch (NullPointerException npe) { // ... }


1 Answers

There is no exception that means "multiple things went wrong", but there's nothing stopping you from creating one. Exceptions are just objects, and they can have members, including something like List<Throwable> getCauses().

like image 103
Paul Hicks Avatar answered Oct 13 '22 00:10

Paul Hicks