Debugging Code: Always Break for Thrown Exceptions
I love working with legacy code, really I do. I find the effort of trying to put myself mindset of the people who originally coded the applications enjoyable. It is somewhat satisfying to be able to get enough of a feel for the code to get a feel for what they were attempting to do as well as what got done. In most cases, it is quite easy to see which libraries and sections were implemented first, and which were either rushed to completion or tacked on as an afterthought. It often makes me spend the extra 15 minutes to fully implement something rather than simply patching over a flaw and planning on implementing the ‘real code’ at some mythic future date. Coming in cold to a project, doing a search for TODO is a good start, but I have also found a lot of cases where that isn’t good enough; so, I have begun setting Visual Studio (VS) to break on any thrown exception. If you aren’t familiar with how to change the way VS handles exceptions in debug mode, here is where you can make the changes:
Doing this helps me track down gems like this (from actual code, I made minor changes to keep from exposing client specific information):
//TEMPORARY - make sure the ID contains at least one alpha
try
{
int i = int.Parse(newID);
newID = newID.Remove(4, 1).Insert(2, "X");
}
catch { }
To be fair to the coder, TryParse has only been in the framework since 2.0, and this code could well have have begun life as a 1.1 application, but the TEMPORARY in the comment was obviously overly optimistic. My solution was to replace the above with:
int i;
//make sure the ID contains at least one alpha
if (int.TryParse(newID, out i))
{
newID = newID.Remove(4, 1).Insert(2, "X");
}