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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With