#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