Application.SetUnhandledExceptionMode Método

Definición

Indica a la aplicación cómo responder a las excepciones no controladas.

Sobrecargas

SetUnhandledExceptionMode(UnhandledExceptionMode)

Indica a la aplicación cómo responder a las excepciones no controladas.

SetUnhandledExceptionMode(UnhandledExceptionMode, Boolean)

Indica a la aplicación cómo responder a las excepciones no controladas, aplicando opcionalmente el comportamiento específico del subproceso.

Ejemplos

En el ejemplo de código siguiente se establecen controladores de eventos para las excepciones que se producen en Windows Forms subprocesos y excepciones que se producen en otros subprocesos. Establece SetUnhandledExceptionMode para que la aplicación controle todas las excepciones, independientemente de la configuración del archivo de configuración de usuario de la aplicación. Usa el ThreadException evento para controlar las excepciones de subprocesos de la interfaz de usuario y el UnhandledException evento para controlar excepciones de subprocesos que no son de interfaz de usuario. Puesto que UnhandledException no se puede impedir que una aplicación finalice, el ejemplo simplemente registra el error en el registro de eventos de la aplicación antes de la finalización.

En este ejemplo se supone que ha definido dos Button controles, button1 y button2, en la Form clase .

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);
}

SetUnhandledExceptionMode(UnhandledExceptionMode)

Indica a la aplicación cómo responder a las excepciones no controladas.

C#
public static void SetUnhandledExceptionMode (System.Windows.Forms.UnhandledExceptionMode mode);

Parámetros

mode
UnhandledExceptionMode

Valor UnhandledExceptionMode que describe cómo debe comportarse la aplicación si se produce una excepción no detectada.

Excepciones

No puede establecer el modo de excepción después de que la aplicación ya ha creado su primera ventana.

Ejemplos

En el ejemplo de código siguiente se establecen controladores de eventos para las excepciones que se producen en Windows Forms subprocesos y excepciones que se producen en otros subprocesos. Establece SetUnhandledExceptionMode para que la aplicación controle todas las excepciones, independientemente de la configuración del archivo de configuración de usuario de la aplicación. Usa el ThreadException evento para controlar las excepciones de subprocesos de la interfaz de usuario y el UnhandledException evento para controlar excepciones de subprocesos que no son de interfaz de usuario. Puesto que UnhandledException no se puede impedir que una aplicación finalice, el ejemplo simplemente registra el error en el registro de eventos de la aplicación antes de la finalización.

En este ejemplo se supone que ha definido dos Button controles, button1 y button2, en la Form clase .

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);
}

Comentarios

A menudo no es factible detectar todas las excepciones producidas por Windows Forms. Con este método, puede indicar a la aplicación si debe detectar todas las excepciones no controladas iniciadas por Windows Forms componentes y seguir funcionando, o si debe exponerlas al usuario y detener la ejecución.

Llame SetUnhandledExceptionMode a antes de crear una instancia del formulario principal de la aplicación mediante el Run método .

Para detectar excepciones que se producen en subprocesos no creados y que pertenecen a Windows Forms, use el UnhandledException controlador de eventos.

Consulte también

Se aplica a

.NET Framework 4.8.1 y otras versiones
Producto Versiones
.NET Framework 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

SetUnhandledExceptionMode(UnhandledExceptionMode, Boolean)

Indica a la aplicación cómo responder a las excepciones no controladas, aplicando opcionalmente el comportamiento específico del subproceso.

C#
public static void SetUnhandledExceptionMode (System.Windows.Forms.UnhandledExceptionMode mode, bool threadScope);

Parámetros

mode
UnhandledExceptionMode

Valor UnhandledExceptionMode que describe cómo debe comportarse la aplicación si se produce una excepción no detectada.

threadScope
Boolean

true para establecer el modo de excepción del subproceso; de lo contrario, false.

Excepciones

No puede establecer el modo de excepción después de que la aplicación ya ha creado su primera ventana.

Ejemplos

En el ejemplo de código siguiente se establecen controladores de eventos para las excepciones que se producen en Windows Forms subprocesos y excepciones que se producen en otros subprocesos. Establece SetUnhandledExceptionMode para que la aplicación controle todas las excepciones, independientemente de la configuración del archivo de configuración de usuario de la aplicación. Usa el ThreadException evento para controlar las excepciones de subprocesos de la interfaz de usuario y el UnhandledException evento para controlar excepciones de subprocesos que no son de interfaz de usuario. Puesto que UnhandledException no se puede impedir que una aplicación finalice, el ejemplo simplemente registra el error en el registro de eventos de la aplicación antes de la finalización.

En este ejemplo se supone que ha definido dos Button controles, button1 y button2, en la Form clase .

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);
}

Comentarios

A menudo no es factible detectar todas las excepciones producidas por Windows Forms. Con este método, puede indicar a la aplicación si debe detectar todas las excepciones no controladas iniciadas por Windows Forms componentes y seguir funcionando, o si debe exponerlas al usuario y detener la ejecución.

Llame SetUnhandledExceptionMode a antes de crear una instancia del formulario principal de la aplicación mediante el Run método .

Cuando threadScope es true, se establece el modo de excepción de subproceso. El modo de excepción de subproceso invalida el modo de excepción de aplicación si mode no está establecido Automaticen .

Cuando threadScope es false, se establece el modo de excepción de aplicación. El modo de excepción de aplicación se usa para todos los subprocesos que tienen el Automatic modo . Establecer el modo de excepción de aplicación no afecta a la configuración del subproceso actual.

Para detectar excepciones que se producen en subprocesos no creados y que pertenecen a Windows Forms, use el UnhandledException controlador de eventos.

Se aplica a

.NET Framework 4.8.1 y otras versiones
Producto Versiones
.NET Framework 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