Thursday, March 11, 2010

Re-throwing exceptions in C#



What is the difference between the following two blocks of code?

// #1
void HandleException()
{
    try
    {
        //Do something...
    }
    catch (Exception e)
    {
        throw e;
    }
}

// #2
void HandleException()
{
    try
    {
        //Do something...
    }
    catch (Exception e)
    {
        throw;
    }
}

Both blocks catch and re-throw an exception. The first block re-throws the caught exception, the second block does not specify anything to throw. The main difference between these blocks becomes apparent when the exception is logged higher up in the call stack. The stack trace for the first code block will be missing anything that came before the throw. The second code block will contain the full stack trace. This can be the difference between life and death when trying to diagnose an issue in production.

1 comment:

  1. true.

    Actually this is a very popular interview question.

    Basharat

    ReplyDelete