Search code examples
c#.netexceptionrethrow

Best practices for catching and re-throwing .NET exceptions


What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?

try
{
    //some code
}
catch (Exception ex)
{
    throw ex;
}

Vs:

try
{
    //some code
}
catch
{
    throw;
}

Solution

  • The way to preserve the stack trace is through the use of the throw; This is valid as well

    try {
      // something that bombs here
    } catch (Exception ex)
    {
        throw;
    }
    

    throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement.

    Mike is also correct, assuming the exception allows you to pass an exception (which is recommended).

    Karl Seguin has a great write up on exception handling in his foundations of programming e-book as well, which is a great read.

    Edit: Working link to Foundations of Programming pdf. Just search the text for "exception".