Sunday, July 16, 2006

When Is a Throw Not a Rethrow?

I found this blog post from Chris Burrows .Net Blog ,but this snippet is originally from Craig Andera's blog.. Check this out, It is very important indeed.

Reading made me remember about the first time I had an issue in production, and I was throwing the exception in the first way and could understand why I wasn't getting all of the stack trace information. Definitely, a good thing to remember.

There’s something I ran into recently that even experienced programmers can get wrong. We were adding error handling to something, and I saw this in the code:

catch (Exception e)
{
LogError(e);
throw e;
}

The idea being that we log all errors in our components, but then throw them again to let the higher level systems actually figure out what to do. This works well. The problem comes in with the throw – it actually works much better to do this:

catch (Exception e)
{
LogError(e);
throw; // Rethrows the exception we just caught
}

Notice the absence of an argument to the throw statement in the second variation.

The difference between these two variations is subtle but important. The second variation is the only one that actually re-throws the original exception. Meaning that the exact same information is passed along up the stack. With the first variation, the higher level caller isn’t going to get all the information about the original error.

For example, the call stack in the exception is replaced with a new call stack that originates at the “throw e” statement – which is not what we want to record.

1 comment:

Madhawa said...

Well... This is one of the best practises we should follow when exception handling