Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an AggregateException in my own code

Tags:

How should I go about collecting exceptions and putting them into an AggregateException to re-throw?

For my specific code, I have a loop and will have zero or more exceptions thrown from a part of the code. I was hoping to just add the new exceptions to the AggregateException as they arise, but the documentation sort of indicates that it should be constructed with all the Exceptions at once (there is no method to add an Exception to the object).

And what about creating a new AE every time and just including the previous AE in the list of exceptions? Seems a hokey way to do it.

Any better ideas?

like image 306
Pat Avatar asked Jun 11 '10 19:06

Pat


People also ask

How do you flatten AggregateException?

To avoid having to iterate over nested AggregateException exceptions, you can use the Flatten method to remove all the nested AggregateException exceptions, so that the InnerExceptions property of the returned AggregateException object contains the original exceptions.

When would you use an aggregate exception?

AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query.

Does await throw AggregateException?

When using await, it's going to unwrap the first exception and return it, that's why we don't hit the catch (AggregateException e) line.

Does throw code stop?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.


1 Answers

Are you talking about something like this?

var exceptions = new List<Exception>(); foreach (var item in items) {     try {         DoSomething(item);      } catch (Exception ex) {         exceptions.Add(ex);     } }  if (exceptions.Count > 0)     throw new AggregateException(         "Encountered errors while trying to do something.",         exceptions     ); 

Seems like the most logical way to me.

like image 161
Dan Tao Avatar answered Sep 20 '22 12:09

Dan Tao