Debugging exceptions in VS2005 and VS2008
There's a really simple technique I use to debug exceptions in Visual Studio, and I can't even count the number of people I've shown it to over the last few years. Here is the scenario: an exception gets thrown somewhere deep within your program, goes through some error handling, perhaps gets logged, and by the time it gets up to the level where you're aware of it, you have no idea what it means. This could be because you neglected to include enough information in the exception, or it could be because some library you're using choked on bad input, or any number of things. The problem is that you have no idea what caused the exception.
Below is a simple program that throws an exception when you click a button.
Here's what you get when you run it. Not terribly useful.
This message clearly doesn't contain enough information. If we hadn't handled the exception in our code, VS would have stopped execution an notified us of an unhandled exception, and we could dig into it from there. However, as long as we handle it, VS will continue execution without notifying us. In the case of this example, we could open up the editor while the message box is displayed, pause execution, and walk up the call stack, but there is a simpler way.
If we go into the Debug menu and click on Exceptions..., the following dialog comes up:
These are the default settings under the Exceptions menu. The column of check boxes on the right indicates that VS will break when there is an unhandled exception of any of the listed types. If we check any of the boxes in the left column, VS will break when any of the listed types is thrown. I usually only use this when I'm trying to track down a nasty exception, because certain programs and libraries throw exceptions under normal working conditions.
Here is what my exceptions screen looks like:
If we go back and run the example again, we'll drop into debug mode as soon as the exception is thrown, and we can start debugging right from the site of the problem.
The example project is available online: ExceptionExample.zip
2 comments:
For Some strange reason, my menu is much shorter and doesnt have the exception option on the menu. Any ideas why?
Glen,
I've seen installs of VS that didn't end up including the Exceptions menu item, but I'm not entirely sure why. Are you using Visual C++, possibly?
At any rate, if you click on Tools->Customize, and then the "Debug" category, there should be an "Exceptions" option in the Commands window. You can drag this up to your Debug window, and you'll be ready to rock.
Post a Comment