Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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.

Tip

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata