June 7, 2006
We must be able to pause execution of our application to debug it effectively. We use breakpoints most of the time to tell the debugger where to stop.
We usually want the debugger to pause when our application throws an exception. The debugger breaks on an exception by default unless our code catches that exception. In other words, the debugger will not stop if the line that throws the exception is wrapped in a Try/Catch block. Execution continues and we may be unable to discover where or even if the exception was thrown.
We can configure the Visual Studio debugger to break whenever an exception is thrown, even if it is caught in a Try/Catch block. Press Ctrl-Alt- E; Visual Studio presents the Exceptions dialog. The dialog displays a tree of exceptions, categorized by general type.
Each exception (or exception type) is paired with two checkbox columns. The column titled "Thrown" is unchecked by default; if checked, the debugger should pause whenever the exception is thrown. The second, "User-unhandled", is typically checked and tells the debugger to pause if the exception is not handled (e.g., is not caught in a Try/Catch block).
We can tell the debugger to break on a broad category of exceptions (such as break on all Common Language Runtime Exceptions), or a category of exceptions from a namespace (such as any System.IO exception), or on a specific exception (like System.IO.IOException) by checking the "Thrown" checkbox as shown in Figure 1.
We can add other exceptions to this list - such as DevForce or our own custom exception - by clicking the "Add" button. In the ensuing New Exception dialog (Figure 2):
- Set the Type to Common Language Runtime Exceptions
- Enter the fully qualified name (ex: MyNamespace.MyException)
- Click OK
Finally, the debugger will not stop for an exception thrown in a method with a debugger directive attribute such as System.Diagnostics.DebuggerStepThrough. You will have to remove the attribute or comment it out to debug into that method.