Application.ThreadException Event


Occurs when an untrapped thread exception is thrown.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

static member ThreadException : IEvent<ThreadExceptionEventHandler,

This event allows your Windows Forms application to handle otherwise unhandled exceptions that occur in Windows Forms threads. Attach your event handlers to the ThreadException event to deal with these exceptions, which will leave your application in an unknown state. Where possible, exceptions should be handled by a structured exception handling block.

You can change whether this callback is used for unhandled Windows Forms thread exceptions by setting SetUnhandledExceptionMode. To catch exceptions that occur in threads not created and owned by Windows Forms, use the UnhandledException event handler.


To guarantee that no activations of this event are missed, you must attach a handler before you call Application.Run.


Because this is a static event, you must detach your event handlers when your application is disposed, or memory leaks will result.

The following code example sets event handlers for exceptions that occur on Windows Forms threads and exceptions that occur on other threads. It sets SetUnhandledExceptionMode so that all exceptions are handled by the application, regardless of the settings in the application's user configuration file. It uses the ThreadException event to handle UI thread exceptions, and the UnhandledException event to handle non-UI thread exceptions. Since UnhandledException cannot prevent an application from terminating, the example simply logs the error in the application event log before termination.

This example assumes that you have defined two Button controls, button1 and button2, on your Form class.

No code example is currently available or this language may not be supported.


for the immediate caller to call unmanaged code when adding a handler to this event. Associated enumeration: SecurityPermissionFlag.UnmanagedCode

.NET Framework
Available since 1.1
Return to top