Catching and Re-throwing Exceptions


When catching exceptions, you may want to log some exception information but afterwards pass on the same exception to the caller. Logging information about the exception requires a catch block. Catching the exception nullifies the effect of the exception and lets the program continue executing normally after the catch block executes.

To reactivate the exception for the caller:

  • Inside the catch block (either for a general exception or for a specific exception) type throw followed by a semicolon ( Figure 11.25 ).

    Figure 11.25 While throw ; by itself looks awkward , it's a quick way of re-throwing the same exception. Alternatively, you could just write throw ex; in the code here.
     public void OrderChecks(int Amount) {   try   {      MakeWithdrawal(5.00);   }   catch (AccountOverdrawnException ex)   {      LogProblemAccount(ex.AccountNumber);  throw;  } } 

graphics/tick.gif Tip

  • Alternatively you can allow the original exception to dissipate and generate a new exception. If you still want to provide information about the original exception you could chain the exceptions as illustrated in "Building an Exception Chain."




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