Inner Exceptions in C#

There is a property of exception class which is called inner exception. There is nesting of Exception within exception.

For Example : Exception A has -> Exception B , Exception C , Exception D etc…. and we are to check if exception C has occurred then ignore the exception.

 catch (AggregateException ace)
 {
    if (ace.InnerExceptions != null && ace.InnerExceptions.GetType().Name.Equals("Exception C"))
        {
          trace.TraceMessage(Caller.Info(), LogMessageLevel.Information, $"Task {task.Id} associated with ErrorCode : {ace.Message}. Ignoring the exception as it is a transient error");
        }
 }

This way we can loop through inner exception and perform certain operation.
Other Example would be that the catch clause itself throws another exception

namespace ConsoleApp1
{
    public class Program
    {
		public static void Main(string[] args)
        {
            try
            {
                var exceptions = new List<Exception>();

                exceptions.Add(new ArgumentException("Argument Exception Message"));
                exceptions.Add(new NullReferenceException("Null Reference Exception Message"));

                throw new AggregateException("Aggregate Exception Message", exceptions);
            }
            catch (AggregateException e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }
    }
}

Above program will give you following error:

To Access all the Exception we could use:

catch (AggregateException ex)
{
    foreach (Exception innerException in ex.InnerExceptions)
    {
        Console.WriteLine(innerException.Message);
    }
}

This way we can perform several operation using inner exception.

Thanks 🙂