Visual Studio debugger fails to catch unhandled exception for a Windows Form or WPF Application?
Ever begin debugging a Windows Form to have the form close suddenly without the debugger alerting you to the exception? Or have you ever been stepping through the Form_Load event handler (or a method called by the Form_Load event handler) in a WPF application only to have it unexpectedly bring up the form instead of stepping to the next line? If you have, chances are you were running an x64 version of Windows… “yes? ”, keep reading to learn why; “no?” you are encountering a different issue and please let us know about it through Microsoft Connect.
Why can’t the debugger catch/break on my unhandled exception on x64 versions of Windows?
The reason this happens on x64 versions of Windows is a design decision by the Windows operating system; x64 versions of Windows do not allow user mode exceptions to propagate post a kernel transition on the call stack. What happens is when an exception is thrown in an application, it travels backward on the call stack until it either reaches an exception handler or the application’s “Main()” method. If the exception reaches the application’s “Main()” method without being handled, the debugger recognizes that the exception went unhandled and breaks the application where the exception occurred. As shown below, the Form_Load method causes a kernel transition, so when an exception thrown in a Form_Load method reaches the kernel frame on the callstack, the operating system catches the exception. Since the exception is caught before it reaches the “Main()” method, from the debugger’s perspective the exception was caught—the debugger is unable to determine that the exception was caught by the operating system , not the user code.
How can I tell if this is my problem?
This problem can manifest itself in different ways depending on the type of exception. Both Windows Forms, and WPF applications have exception handling code in the underlying framework that will catch certain types of exceptions (e.g. NullReferenceException), so in some cases your application will crash with an unhandled exception, in other cases the form will load and appear, however the Form_Load method (and all subsequent calls) will not have correctly run to completion. There will however be a message in the “Output” window that “A first Chance exception of type ‘<exception type>’ occurred in <application’s name>”
Unfortunately there isn’t a lot the debugger can do in this case since the operating system catches the exception (explained above). The workaround in Visual Studio is to enable “First Chance” exceptions for the exception types that are being thrown in the Form_Load method. To to this:
- Navigate to the “Debug” menu, and select “Exceptions”
- Check the “Thrown” box for the “Common Language Runtime Exceptions” row. (Note: You can expand the Exceptions using the “+” sign and only check the "Thrown” box for the desired exceptions")