#914 – Using the Debugger to Break when an Exception Is Thrown

By default, if you have an exception handler defined, the debugger in Visual Studio will not break (i.e. stop) at the point where an exception is thrown.

You can, however, configure Visual Studio to break at the point when the exception is thrown.  To enable breaking when an exception is thrown, do the following:

  • From the Debug menu, select Exceptions…

914-001

  • Find the specific type of exception for which you want the debugger to break and click on the Thrown column.  You can select an entire class of exceptions, or a specific exception type.  In the example below, we select all Common Language Runtime Exceptions.

914-002

  • Click the OK button

Now, when you run in debug mode, the debugger will display a dialog at the point where an exception is thrown and give you a chance to break (stop).

914-003

 

If you do break, you can then examine the exception object.

914-004

 

#875 – Looking at the Call Stack after Catching an Exception

After an exception is thrown, it bubbles up the call stack until a handler that can handle the exception is found.  If you set a breakpoint in an exception handler, you can then use the debugger in Visual Studio to examine the call stack, as it existed at the time that the exception was thrown.

In the example below, we’ve hit a breakpoint that we set in an exception handler.  If we examine the Exception variable passed to the handler, we see that an exception of type ArgumentException has been thrown.

Notice that we can also look at the StackTrace property in the debugger.  It contains text describing the call stack at the time that the exception was thrown.  You can click on the magnifying glass icon to see the stack trace formatted in a way that’s easier to read.

In the example, we see that Dog.Bark threw the exception.

875-001