.NET Tip of The Day
Learn one new .NET trick every day
Login or Join
.NET Tips & Tricks Community RSS

Those who prefer reading this site through RSS now can also subscribe for updates to .NET Tips & Tricks Community.

Don’t clear the stack trace when re-throwing an exception

Often, we need to put some exception handling on catch blocks (e.g., to rollback a transaction) and re-throw the exception. There are two ways of doing it. The wrong way:

    try

    {

        // Some code that throws an exception

    }

    catch (Exception ex)

    {

        // some code that handles the exception

        throw ex;

    }

Why is this wrong? Because, when you examine the stack trace, the point of the exception will be the line of the “throw ex;“, hiding the real error location. Instead of “throw ex;“, which will throw a new exception and clear the stack trace, simply use "throw;":

    try

    {

        // Some code that throws an exception

    }

    catch (Exception ex)

    {

        // some code that handles the exception

        throw;

    }

If you don’t specify the exception, the throw statement will simply rethrow the very same exception the catch statement caught. This will keep your stack trace intact, but still allows you to put code in your catch blocks.

8/21/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.