Essential C# Exception Handling  Suggest an edit

Aggregate exceptions multiple exceptions from one method

Who says you cannot throw multiple exceptions in one method. If you are not used to playing around with AggregateExceptions you may be tempted to create your own data-structure to represent many things going wrong. There are of course were another data-structure that is not an exception would be more ideal such as the results of a validation. Even if you do play with AggregateExceptions you may be on the receiving side and always handling them not realizing they can be of use to you.

It is quite plausible to have a method execute and even though it will be a failure as a whole you will want to highlight multiple things that went wrong in the exceptions that are thrown. As an example this behavior can be seen with how Parallel methods work were a task broken into multiple threads and any number of them could throw exceptions and this needs to be reported. Here is a silly example of how you could benefit from this:

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 happended during execution", exceptions);
    }
}


Table Of Contents
22 Enum
25 GUID
75 Exception Handling
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close