Building an Exception Chain


In certain instances, a single method call may cause multiple related errors to occur. A developer may choose to provide the caller with a chain of errors that report all the exceptions that were triggered. It's called an error chain because the developer catching the exception only sees one of the exceptions in the chain, then the developer uses the InnerException property to get the next exception in the chain. Using the InnerException object, the developer can ask that object for its InnerException and so on, until InnerException returns null. The difficult part of chaining exceptions is that the InnerException property is read-only. This means that chaining exceptions is not just a matter of setting an exception object's InnerException property.

To build an exception chain:

  1. Inside a catch block that captures a specific exception, create a new exception object to throw as the new exception.

  2. In the parameters for the constructor of the new exception object, pass the exception's error message followed by the variable storing the original exception ( Figure 11.26 ).

    Figure 11.26 The only way to nest the exceptions is to pass the previous exception up to the base in the constructor.
     class AccountOverdrawnException : ApplicationException {    public AccountOverdrawnException() {} } class OrderChecksException : ApplicationException {  public OrderChecksException(   string msg,   Exception inner) :   base(msg,inner)  {    } } class Checking {    public void OrderChecks(int Amount)    {       try       {          MakeWithdrawal(5.00);       }       catch (  AccountOverdrawnException ex  )       {  throw new OrderChecksException(   "Unable to order checks",ex);  }    } } 

graphics/tick.gif Tip

  • As you can see from the example, it's a good idea to add a constructor that enables the caller to set the inner exception property. In the constructor for your class, simply pass the inner exception object to your base constructor.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net