Managing Unhandled Exceptions in .NET

using System;
using System.Threading;

public class Form1 : System.Windows.Forms.Form
{
    // ...(omitted)

    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main()
    {
        // Subscribe to thread (unhandled) exception events
        ThreadExceptionHandler handler =
            new ThreadExceptionHandler();

        Application.ThreadException +=
            new ThreadExceptionEventHandler(
                handler.Application_ThreadException);

        // Load the form
        Application.Run(new Form1());
    }

    ///
    /// Adds default name to text box.
    ///
    private void btnAdd_Click(object sender, EventArgs e)
    {
       
        // Generate handled exception
        //Add();
       
        // Generate unhandled exception
        AddWithUnhandledException();
    }

    ///
    /// Removes name from text box.
    ///
    private void btnRemove_Click(object sender, EventArgs e)
    {
        txtName.Clear();
    }

    ///
    /// Adds default name to text box.
    /// Throws handled exception.
    ///
    private void Add()
    {
        try
        {
            txtName.Text = "Kevin";
            throw new InvalidOperationException(
                "Invalid operation.");
        }
        catch (System.Exception ex)
        {
            DisplayError(ex);
        }
    }

    ///
    /// Adds default name to text box.
    /// Throws unhandled exception.
    ///
    private void AddWithUnhandledException()
    {
        txtName.Text = "Kevin";
        throw new InvalidOperationException(
            "Invalid operation.");
    }

    ///
    /// Displays exception message.
    ///
    private void DisplayError(Exception ex)
    {
        MessageBox.Show(ex.GetType() + "\n\n" +
            ex.Message + "\n\n" +
            ex.StackTrace,
            "Error",
            MessageBoxButtons.AbortRetryIgnore,
            MessageBoxIcon.Stop);
    }

} // End Form1

///
/// Handles a thread (unhandled) exception.
///
internal class ThreadExceptionHandler
{
    ///
    /// Handles the thread exception.
    ///
    public void Application_ThreadException(
        object sender, ThreadExceptionEventArgs e)
    {
        try
        {
            // Exit the program if the user clicks Abort.
            DialogResult result = ShowThreadExceptionDialog(
                e.Exception);

            if (result == DialogResult.Abort)
                Application.Exit();
        }
        catch
        {
            // Fatal error, terminate program
            try
            {
                MessageBox.Show("Fatal Error",
                    "Fatal Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Stop);
            }
            finally
            {
                Application.Exit();
            }
        }
    }

    ///
    /// Creates and displays the error message.
    ///
    private DialogResult ShowThreadExceptionDialog(Exception ex)
    {
        string errorMessage=
            "Unhandled Exception:\n\n" +
            ex.Message + "\n\n" +
            ex.GetType() +
            "\n\nStack Trace:\n" +
            ex.StackTrace;

        return MessageBox.Show(errorMessage,
            "Application Error",
            MessageBoxButtons.AbortRetryIgnore,
            MessageBoxIcon.Stop);
    }
} // End ThreadExceptionHandler

posted on 2009-08-04 09:45  chuncn  阅读(238)  评论(0编辑  收藏  举报

导航