First off, Scott, this is not a post about baseball so you can stop reading.
Ok, sorry about that folks. Now, back to business.
This post is about the proper way to do a try/catch/rethrow in C#. While reviewing code recently, I kept running into code like this (some of it no doubt my own code from way back):
try
{
// Some dangerous code.
...
}
catch ( SomeException ex )
{
// Do something to process exception.
...
// Rethrow.
throw ex;
}
The problem with this is that the "throw ex" statement causes the original stack information for the exception to be lost. So now, the exception will appear to originate from the rethrow line which can be very frustrating when trying to track down exactly what caused the exception. So, unless you need to wrap the exception with a new exception (to provide more info), the proper technique to rethrow looks something like this:
try
{
// Some dangerous code.
...
}
catch ( SomeException )
{
// Do something to process exception.
...
// Rethrow.
throw;
}
By using the simple "throw;" instead of "throw ex;", the original exception will be bubbled up and all stack information stays in tact.
Notice also that in the code above, the catch statement does not need to declare the variable, ex, since we don't need it. This avoids those nasty, nagging compiler warnings about declaring a variable that is never used.
Moral of the story (as always): avoid your exes, they're nothing but trouble.
Now, Play ball!