Re-throwing Exceptions

This is one of my favourite interview questions – I’m often surprised by the number of candidates who get this wrong.  Let’s see how you do.

What’s the difference between the following code snippets?

try
{
    DoSomething();
}
catch (SomeException ex)
{
    throw ex;
}
try
{
    DoSomething();
}
catch (SomeException ex)
{
    throw;
}

The answer is that the first snippet destroys the stack trace for the exception while the second snippet keeps it intact.  This can be a real pain when trying to track down a specific issue – in this case the log files will point you to the line of code where you are re-throwing the exception instead of the line where the original exception occurs.  So always use the second code snippet.

Happy coding.