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.
|
|
|