7.12. 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 andthe 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 handler will not catch unhandled exceptions on worker threads constructed by the program 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 a WinForms application, add the following code to the Main function in your application:
static void Main( ) { // Adds the event handler to catch any exceptions that happen // in the main UI thread. Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access