BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

Getting a Base Exception

When using a pattern where caught exceptions are wrapped within new exceptions and rethrown, it may be necessary to examine the originating exception object. The Exception class includes a method that makes this simple to achieve.

When using a pattern where caught exceptions are wrapped within new exceptions and rethrown, it may be necessary to examine the originating exception object. The Exception class includes a method that makes this simple to achieve.

GetBaseException

When you are working with deeply layered software you may use a pattern for exception handling where a caught exception is wrapped within another exception object and rethrown. Each time an exception is thrown, additional information may be added so that the final exception handler has enough data to take the best action for graceful recovery or event logging.

This pattern can lead to deeply nested exceptions where the final exception contains the most diagnostic data but the initial exception holds some information that you require. Handily, the .NET framework's Exception class, from which all other exception types are derived, includes a method that assists in obtaining the originating exception. The GetBaseException method recursively obtains the InnerException property until an exception that has no inner exception is found. This is the base exception that is returned. If the current exception has no inner exception, it is returned.

To demonstrate, try running the following code. This simulates a layered application by manually creating three exceptions, linking them via the InnerException property. The third exception is thrown and caught and its base exception obtained using the GetBaseException method.

try
{
    var exception1 = new NullReferenceException("First Exception");
    var exception2 = new ArgumentNullException("Second Exception", exception1);
    var exception3 = new InvalidOperationException("Third Exception", exception2);
    throw exception3;
}
catch (Exception ex)
{
    var baseException = ex.GetBaseException();
    Console.WriteLine(baseException.Message);       // "First Exception"
}
30 November 2011