#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