This post originated from an RSS feed registered with .NET Buzz
by Brad Wilson.
Original Post: Re-Throwing Exceptions
Feed Title: The .NET Guy
Feed URL: /error.aspx?aspxerrorpath=/dotnetguy/Rss.aspx
Feed Description: A personal blog about technology in general, .NET in specific, and when all else fails, the real world.
I just picked up Test Driven Development in Microsoft .NET, a book which I'm enjoying a lot. However, I ran across a piece of code that I simply don't like, and I thought I'd share. I hate to pick on sample code, but this is one time where I think it's worth it.
What bugs me is that "throw exception;" line. In my mind, that code is always wrong, because it throws away valuable information. It's not your exception, but you're "laying claim" to it by pushing in your own stack trace, killing the potentially valuable information in the original stack trace.
In my opinion, you should decide which of the following statements is true, and use different code instead.
1. You are insignificant in the exception chain
If you're catching the exception just to do cleanup, and the user shouldn't really be worried about the fact that you caught it, you should re-throw using this code instead:
This preserves the original calling stack. Nobody knows you were involved, and they can trace back to the exception from its true origin without being diverted into your cleanup code. (I'd place the example above in this category.)
2. You are significant in the execution chain
If you want to be part of the exception chain, then you should re-package the exception with your own, and assign the old one as the inner exception:
catch(Exception exception)
{
TransactionManager.Rollback();
throw new MyAppropriateException(exception);
}
You turn the general exception into a specific one, while preserving the original inner exception so that it can continue to be traced back to the origin.