
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Dealing with Unhandled Exceptions in WinForms Applications
|
431
7.20 Dealing with Unhandled Exceptions
in WinForms Applications
Problem
You have a WinForms-based application in which you want to catch and log any
unhandled exceptions on any thread.
Solution
You need to hook up handlers for both the System.Windows.Forms.Application.
ThreadException
event and the System.AppDomain.UnhandledException event. Both of
these events need to be hooked up, as the WinForms support in the Framework does
a lot of exception trapping itself. It exposes the
System.Windows.Forms.Application.
ThreadException
event to allow you to get any unhandled exceptions that happen on
the UI thread that the WinForms and their events are running on. In spite of its
deceptive name, the
System.Windows.Forms.Application.ThreadException event han-
dler will not catch unhandled exceptions on worker threads constructed by the pro-
gram or from
ThreadPool threads. In order to catch all of those possible routes for
unhandled exceptions in a WinForms application, you need to hook up a handler for
the
System.AppDomain.UnhandledException event that does catch those (but not the UI
thread ones that
System.Windows.Forms.Application.ThreadException does).
To hook up the necessary event handlers to catch all of your unhandled exceptions
in