Arian Kulp's Blog
opinion, insight, and occasional code

Battling unhandled exceptions

Thursday, January 25, 2007 8:50 AM

As I was debugging an in-progress sample application, I was having trouble with an unhandled exception.  The application would bomb on an Invoke statement, when clearly there was no problem at that point:

Image 1: An unexpected exception (click to see full-size)

I had previously created a delegate pointing to a given method, and a delegate for the callback method.  From a delegate instance, you can call BeginInvoke to cause the method to be queued on a background thread.  When the operation completes, your callback method is invoked.  It's a beautiful way to dispatch low-priority programming tasks without writing your own threading code.  The only caveat though, is a Windows forms application has threading restrictions regarding interacting with UI elements.  When the callback method is invoked, you can't just start modifying the UI.  Instead, you must call Invoke on the form itself, passing it your delegate.  That queues up the method to be executed on the UI's thread (the one with the ever-important message pump!).  Confused yet?

Unhandled exceptions on background threads may not always manifest themselves as you expect.  If you get the exception helper dialog and can't make sense of it, you may be wondering why it won't show you the actual line of code (and even the Call Stack pane probably won't help in this case due to the multiple threads).  The simple solution is to instruct the debugger to stop execution as soon as an unhandled exception occurs.  By default, the debugger only stops you if the exception is unhandled.

To make this change, click the Debug | Exceptions menu command.  From there, you have great control over when the debugger breaks execution.  The easiest route to take is to click the Thrown check for Common Language Runtime Exceptions.  This means that as soon as the exception is thrown you want to stop and examine it.  You can also drill into the various groups of exception types and check or uncheck for specific exceptions.

Figure 2: Breaking when the exception is thrown

This very quick and easy fix will help you locate that pesky exception faster.  Now you can fix the issue with all information at hand!  It also has the side effect of breaking on exceptions even when there is a catch cause.  Don't worry though, just continue debugging in that case -- the application won't exit.  That's where customizing for specific exception types may come in handy.

Comments have been closed on this topic.