List of Exceptions

3

How to implement a class so that I can add an exception to an exception list.

This class would be used for the case below, for example:

In the validation method it can return one or more errors, so each error is added an exception in the list and at the end of the validation this list will fall within the specific catch of the type of this list.

    
asked by anonymous 11.02.2016 / 14:16

3 answers

5

You can use AggregateException for do what you want:

try
{
    List<Exception> excepcoes = new List<Exception>();
    excepcoes.Add(new ArgumentException("argumento", "argumento invalido"));
    excepcoes.Add(new ArgumentNullException("argumento nulo"));
    excepcoes.Add(new InvalidCastException("operacao invalida"));

    throw new AggregateException(excepcoes);
}
catch(AggregateException aEx)
{
    foreach(var ex in aEx.InnerExceptions)
    {
        Console.WriteLine("{0}: {1}\n", ex.GetType(), ex.Message);

        // Output:

        // System.ArgumentException: argumento
        // Parameter name: argumento invalido

        // System.ArgumentNullException: Value cannot be null.
        // Parameter name: argumento nulo

        // System.InvalidCastException: operacao invalida
    }
}

The AggregateException constructor accepts a list of exceptions, which can then be accessed through the .InnerExceptions property.

See here an example in dotFiddle.

    
11.02.2016 / 14:35
1

You create the list just like any other ...

Here's an example: fiddle

        List<Exception> le = new List<Exception>();

        try
        {
            try{
                throw new Exception(" except 1");
            }
            catch(Exception e)
            {
                le.Add(e);
                throw new Exception("except 2");
            }
        }
        catch(Exception e)          
        {
            le.Add(e);
        }

        foreach(var e in le)
        {
             Console.WriteLine(e);
        }
    
11.02.2016 / 14:29
0

You can create an exception by inheriting from Exception , in it, you add an array of Exception or its exception, and throw / catch to this one. when giving catch you can show all exceptions in the list, if any.

    
11.02.2016 / 14:34