Thursday, September 2, 2010

Debugging Visual Basic's UnhandledException event

One of our applications is comprised of numerous C# projects and a single Visual Basic project. The VB project is the entry point into the application. If the legend is true VB was chosen because of the friendliness of the WindowsFormsApplicationBase class. We've got a global exception handler hooked up to the UnhandledException event. This works well except when you want to debug the global exception handler. The "Visual Basic compiler prevents applications that are built for debugging from raising this event, to enable a debugger to handle the unhandled exceptions. This means that if you are testing your application by running it under the Visual Studio Integrated Development Environment debugger, your UnhandledException event handler will not be called." That's a problem.

Stackoverflow gave me an idea that worked out well in my case. I added code to the WindowsFormsApplicationBase.Startup event handler that- if DEBUG is defined and the debugger is attached- adds a handler for the AppDomain.UnhandledException event. (The conditional logic might be overly defensive but I can't take any chances with this mature, stable application.) When the AppDomain.UnhandledException event handler fires, it merely calls the WindowsFormsApplicationBase.UnhandledException event handler, where I've set a breakpoint.

        Private Sub AppDomainUnhandledException(ByVal sender As ObjectByVal args As UnhandledExceptionEventArgs)
            Dim ex As Exception = DirectCast(args.ExceptionObject, Exception)
            Dim newArgs As New Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs(False, ex)
            MyApplication_UnhandledException(sender, newArgs)
        End Sub

Now I can step through my changes. Yippee!