Application..::.ThreadException Event Home
This page is specific to:.NET Framework Version:1.12.03.03.54.0
.NET Framework Class Library
Application..::.ThreadException Event

Updated: September 2008

Occurs when an untrapped thread exception is thrown.

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

'Usage

Dim handler As ThreadExceptionEventHandler

AddHandler Application.ThreadException, handler


'Declaration

Public Shared Event ThreadException As ThreadExceptionEventHandler
Remarks

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.

NoteNote:

To use this event, you must attach a handler before you call Application..::.Run.

Caution noteCaution:

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

Examples

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.

        Private newThread As Thread = Nothing

        ' Starts the application. 
        <SecurityPermission(SecurityAction.Demand, Flags:=SecurityPermissionFlag.ControlAppDomain)> _
        Public Shared Sub Main()
            ' Add the event handler for handling UI thread exceptions to the event.
            AddHandler Application.ThreadException, AddressOf ErrorHandlerForm.Form1_UIThreadException

            ' Set the unhandled exception mode to force all Windows Forms errors to go through
            ' our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

            ' Add the event handler for handling non-UI thread exceptions to the event. 
            AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException

            ' Runs the application.
            Application.Run(New ErrorHandlerForm())
        End Sub


        ' Programs the button to throw an exception when clicked.
        Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
            Throw New ArgumentException("The parameter was invalid")
        End Sub

        ' Start a new thread, separate from Windows Forms, that will throw an exception.
        Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button2.Click
            Dim newThreadStart As New ThreadStart(AddressOf newThread_Execute)
            newThread = New Thread(newThreadStart)
            newThread.Start()
        End Sub


        ' The thread we start up to demonstrate non-UI exception handling. 
        Sub newThread_Execute()
            Throw New Exception("The method or operation is not implemented.")
        End Sub


        ' Handle the UI exceptions by showing a dialog box, and asking the user whether
        ' or not they wish to abort execution.
        Private Shared Sub Form1_UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
            Dim result As System.Windows.Forms.DialogResult = _
                System.Windows.Forms.DialogResult.Cancel
            Try
                result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception)
            Catch
                Try
                    MessageBox.Show("Fatal Windows Forms Error", _
                        "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
                Finally
                    Application.Exit()
                End Try
            End Try

            ' Exits the program when the user clicks Abort.
            If result = DialogResult.Abort Then
                Application.Exit()
            End If
        End Sub

        ' Handle the UI exceptions by showing a dialog box, and asking the user whether
        ' or not they wish to abort execution.
        ' NOTE: This exception cannot be kept from terminating the application - it can only 
        ' log the event, and inform the user about it. 
        Private Shared Sub CurrentDomain_UnhandledException(ByVal sender As Object, _
        ByVal e As UnhandledExceptionEventArgs)
            Try
                Dim ex As Exception = CType(e.ExceptionObject, Exception)
                Dim errorMsg As String = "An application error occurred. Please contact the adminstrator " & _
                    "with the following information:" & ControlChars.Lf & ControlChars.Lf

                ' Since we can't prevent the app from terminating, log this to the event log.
                If (Not EventLog.SourceExists("ThreadException")) Then
                    EventLog.CreateEventSource("ThreadException", "Application")
                End If

                ' Create an EventLog instance and assign its source.
                Dim myLog As New EventLog()
                myLog.Source = "ThreadException"
                myLog.WriteEntry((errorMsg + ex.Message & ControlChars.Lf & ControlChars.Lf & _
                    "Stack Trace:" & ControlChars.Lf & ex.StackTrace))
            Catch exc As Exception
                Try
                    MessageBox.Show("Fatal Non-UI Error", "Fatal Non-UI Error. Could not write the error to the event log. " & _
                        "Reason: " & exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop)
                Finally
                    Application.Exit()
                End Try
            End Try
        End Sub


        ' Creates the error message and displays it.
        Private Shared Function ShowThreadExceptionDialog(ByVal title As String, ByVal e As Exception) As DialogResult
            Dim errorMsg As String = "An application error occurred. Please contact the adminstrator " & _
         "with the following information:" & ControlChars.Lf & ControlChars.Lf
            errorMsg = errorMsg & e.Message & ControlChars.Lf & _
         ControlChars.Lf & "Stack Trace:" & ControlChars.Lf & e.StackTrace

            Return MessageBox.Show(errorMsg, title, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
        End Function


.NET Framework Security

Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
See Also

Reference

Change History

Date

History

Reason

September 2008

Removed inaccurate comment indicating that unhandled exceptions in threads other than the main thread do not cause the application to terminate.

Customer feedback.

Community Content

Only the innermost exception is received in the event
Added by:Marqs

Note that only the innermost exception of an exception chain reaches the ThreadException event handler.

For example, if a FileNotFoundException is thrown and you catch it in your code and throw another exception which wraps the FileNotFoundException, the Exception property of the ThreadExceptionEventArgs object in the ThreadException event handler holds the FileNotFoundException, not the wrapping exception as you might expect.

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View