Microsoft Docs

ThreadExceptionEventArgs Class

System.Threading

Summary

Represents the exception that is thrown when a thread encounters an error.

Syntax

public class ThreadExceptionEventArgs : EventArgs

Constructors

public ThreadExceptionEventArgs (Exception t)

Initializes a new instance of the ThreadExceptionEventArgs class with the specified exception.

Parameters

t
The exception that is thrown when a thread encounters an error.

Properties

public Exception Exception { get; }

Gets the exception that is thrown when a thread encounters an error.

Remarks

The ThreadExceptionEventArgs class is used to pass exception information to an event handler when a thread encounters an error. The Exception property of the ThreadExceptionEventArgs object contains the exception that was thrown.

This class is used by the ThreadException event, which is raised when an unhandled exception occurs in a thread.

Requirements

Namespace
System.Threading
Assembly
System.dll

Example

The following example demonstrates how to handle the ThreadException event and use the ThreadExceptionEventArgs object to access the exception information.


using System;
using System.Threading;
using System.Windows.Forms;

public class MainForm : Form
{
    public MainForm()
    {
        this.ThreadException += new ThreadExceptionEventHandler(MainForm_ThreadException);
    }

    private void MainForm_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show($"An unhandled thread exception occurred: {e.Exception.Message}");
        // Handle the exception or terminate the application
    }

    [STAThread]
    public static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Create a thread that will intentionally throw an exception
        Thread errorThread = new Thread(() =>
        {
            throw new InvalidOperationException("Something went wrong in the background thread.");
        });
        errorThread.Start();

        Application.Run(new MainForm());
    }
}