Exact Usage of catch Block in C#

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.

Ebook Download
View all

FileInfo in C#

Read by 9.7k people
Download Now!
Learn
View all