Aggregate exceptions multiple exceptions from one method
suggest changeWho says you cannot throw multiple exceptions from one method? If you are not used to AggregateException, you may be tempted to create your own data structure to represent many things going wrong. There are, of course, cases where a data structure that is not an exception is a better fit, such as validation results. Even if you do use AggregateException, you may only handle it and not realize you can throw it yourself.
A method can fail as a whole while you still want the thrown exceptions to highlight several things that went wrong. Parallel methods do this: a task is split across threads, any number of those threads can throw, and the failures are reported together. Here is a simple example:
public void Run()
{
try
{
this.SillyMethod(1, 2);
}
catch (AggregateException ex)
{
Console.WriteLine(ex.Message);
foreach (Exception innerException in ex.InnerExceptions)
{
Console.WriteLine(innerException.Message);
}
}
}
private void SillyMethod(int input1, int input2)
{
var exceptions = new List<Exception>();
if (input1 == 1)
{
exceptions.Add(new ArgumentException("I do not like ones"));
}
if (input2 == 2)
{
exceptions.Add(new ArgumentException("I do not like twos"));
}
if (exceptions.Any())
{
throw new AggregateException("Funny stuff happened during execution", exceptions);
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents