Recipe 5.2 Indicating Where Exceptions Originate

Problem

You want to be able to clearly distinguish which of your objects threw an exception, to aid in tracking down problems.

Solution

You should rethrow the exception in the catch clause in which the original exception was handled. The throw keyword is used, followed by a semicolon, to rethrow an exception:

 try {     Console.WriteLine("In inner try");     int z2 = 9999999;     checked{z2 *= 999999999;}   } catch(DivideByZeroException dbze) {     Console.WriteLine(@"A divide by zero exception occurred. " +                           "Error message == " + dbze.Message);  throw;  } 

Discussion

Rethrowing a caught exception is useful to inform clients of your code that an error has occurred. Consider the case in which a client application contained the CatchReThrownException method and the ReThrowException method was contained in a separate server application that existed somewhere on the network. When the client application called the ReThrowException method and an error occurred, the server application could handle the exception and continue about its business. However, if this exception forced the server application to abort, it should rethrow the exception so that the client application knows what happened and can deal with the same exception in a graceful manner.

Remember that throwing exceptions is expensive. Try not to needlessly throw and rethrow exceptions since this might bog down your application.




C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

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