Application.ThreadException Événement

Définition

Se produit lorsqu'une exception de thread ininterrompu est levée.

C#
public static event System.Threading.ThreadExceptionEventHandler ThreadException;
C#
public static event System.Threading.ThreadExceptionEventHandler? ThreadException;

Type d'événement

Exemples

L’exemple de code suivant définit des gestionnaires d’événements pour les exceptions qui se produisent sur les threads Windows Forms et les exceptions qui se produisent sur d’autres threads. Il définit SetUnhandledExceptionMode afin que toutes les exceptions soient gérées par l’application, quels que soient les paramètres dans le fichier de configuration de l’application utilisateur. Il utilise l'événement ThreadException pour gérer les exceptions de thread d’interface utilisateur et l'événement UnhandledException pour gérer les exceptions issues de threads autres que celui de l’interface utilisateur. Dans la mesure où UnhandledException ne peut pas empêcher une application de se terminer, l’exemple enregistre simplement l’erreur dans le journal des événements d’application avant l’arrêt.

Cet exemple suppose que vous avez défini deux contrôles Button, button1 et button2, dans votre classe Form.

C#
Thread newThread = null;

// Starts the application.
public static void Main(string[] args)
{
    // Add the event handler for handling UI thread exceptions to the event.
    Application.ThreadException += new ThreadExceptionEventHandler(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.
    AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    // Runs the application.
    Application.Run(new ErrorHandlerForm());
}

// Programs the button to throw an exception when clicked.
private void button1_Click(object sender, System.EventArgs e)
{
    throw new ArgumentException("The parameter was invalid");
}

// Start a new thread, separate from Windows Forms, that will throw an exception.
private void button2_Click(object sender, System.EventArgs e)
{
    ThreadStart newThreadStart = new ThreadStart(newThread_Execute);
    newThread = new Thread(newThreadStart);
    newThread.Start();
}

// The thread we start up to demonstrate non-UI exception handling.
void newThread_Execute()
{
    throw new Exception("The method or operation is not implemented.");
}

// Handle the UI exceptions by showing a dialog box, and asking the user whether
// or not they wish to abort execution.
private static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
    DialogResult result = 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();
        }
    }

    // Exits the program when the user clicks Abort.
    if (result == DialogResult.Abort)
        Application.Exit();
}

// 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 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        Exception ex = (Exception)e.ExceptionObject;
        string errorMsg = "An application error occurred. Please contact the adminstrator " +
            "with the following information:\n\n";

        // Since we can't prevent the app from terminating, log this to the event log.
        if (!EventLog.SourceExists("ThreadException"))
        {
            EventLog.CreateEventSource("ThreadException", "Application");
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "ThreadException";
        myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
    }
    catch (Exception exc)
    {
        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();
        }
    }
}

// Creates the error message and displays it.
private static DialogResult ShowThreadExceptionDialog(string title, Exception e)
{
    string errorMsg = "An application error occurred. Please contact the adminstrator " +
        "with the following information:\n\n";
    errorMsg = errorMsg + e.Message + "\n\nStack Trace:\n" + e.StackTrace;
    return MessageBox.Show(errorMsg, title, MessageBoxButtons.AbortRetryIgnore,
        MessageBoxIcon.Stop);
}

Remarques

Cet événement permet à votre application Windows Forms de gérer les exceptions non prises en charge qui se produisent dans les threads de Windows Forms. Attachez votre gestionnaire d’événements à l’événement ThreadException pour gérer ces exceptions, ce qui laissera votre application dans un état inconnu. Dans la mesure du possible, les exceptions doivent être gérées localement par un bloc structuré de gestion des exceptions.

Vous pouvez choisir si ce rappel doit être utilisé pour les exceptions Windows Forms non gérées en définissant SetUnhandledExceptionMode. Pour intercepter les exceptions qui se produisent dans les threads non créés et détenus par Windows Forms, utilisez l'événement UnhandledException.

Note

Pour garantir qu’aucune activation de cet événement ne soit manquée, vous devez attacher un gestionnaire avant d’appeler Application.Run.

Note

Un seul gestionnaire peut être attaché à cet événement. Si plusieurs gestionnaires sont ajoutés, seul le gestionnaire le plus récemment ajouté est appelé sur une exception non gérée.

Attention

S'agissant d'un événement statique, vous devez détacher vos gestionnaires d’événements lorsque votre application est supprimée, faute de quoi des fuites mémoire vont se produire.

S’applique à

Produit Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10