#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: