#904 – Getting the Innermost Wrapped Exception

When you re-throw an exception, you can create a new exception that wraps the original exception by setting the InnerException property of the new exception to refer to the original exception.

An exception that wraps an inner exception can itself by wrapped.  When you catch an exception, the original cause of the exception might be several levels deep.  You can get to the original exception by looking at the InnerException property of each exception, working your way down until you find one that has a null value for InnerException.

You can also get access to the innermost exception using the Exception.GetBaseException method.  This method just follows the chain of exceptions using the InnerException and stops when it gets to the innermost exception.

                try
                {
                    DoDogStuff();
                }
                catch (ApplicationException wrappedEx)
                {
                    Console.WriteLine("** Main() caught ApplicationException:");
                    Console.WriteLine("  Base exception: ");
                    Console.WriteLine("  {0}", wrappedEx.GetBaseException().ToString());
                }

904-001

#903 – Wrapped Exceptions Can Be Several Levels Deep

When handling an exception, you can wrap the original exception in a new exception that you throw, by setting the InnerException property of the new exception to reference the original exception.

If it makes sense for your application, you can wrap an already-wrapped exception, such that the inner exception itself contains an inner exception.  You might also encounter wrapped exceptions that are several levels deep when using the .NET Framework.

In the example below, a Main method calls a DoDogStuff method.  DoDogStuff in turn calls Dog.Bark, which calls Dog.ReadBarkLog.  The original exception is wrapped, as follows:

  • ReadBarkLog throws an IOException
  • Dog.Bark catches the IOException and wraps it in a DogBarkException
  • DoDogStuff catches the DogBarkException and wraps it in an ApplicationException
  • Main catches the ApplicationException and then has access to both inner exceptions

903-001