Top-level Exception Handling in Windows Forms Applications – Code Listing 1

 

This code listing is available for download. 

 

This is a very basic code example of how to use the ThreadException event to handle exceptions occurring anywhere on the main GUI thread in a Windows Forms application.  My blog article ‘Top-level Exception Handling in Windows Forms Applications’ discusses this in more detail.

 

From looking at the forums it seems many people have problems getting the ThreadException event to fire correctly.  To make sure you can get my example working I have included quite detailed instructions: you probably don’t need these though!

 

1.  Create a new C# Windows Application in Visual Studio 2005, calling it ExceptionHandling1. 

2.  Replace the code in Program.cs with the code below.

 

using System.Windows.Forms;

using System.Threading;

namespace ExceptionHandling1

{

    static class Program

    {

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        static void
Main()

        {

            Application.ThreadException += new ThreadExceptionEventHandler(new ThreadExceptionHandler().ApplicationThreadException);

            Application.Run(new Form1());

        }

        /// <summary>

        /// Handles any thread exceptions

        /// </summary>

        public class ThreadExceptionHandler

        {

            public void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)

            {

                MessageBox.Show(e.Exception.Message, “An exception occurred:”, MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

    }

}

 

3.  Replace the code behind the default Form1 with the code below (Form1.cs):

 

using System;

using System.Windows.Forms;

using System.Threading;

namespace ExceptionHandling1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void throwExceptionButton_Click(object sender, EventArgs e)

        {

            ThrowException();

        }

        private void ThrowException()

        {

            // Note that in general you shouldn’t throw a generic ApplicationException

            // but should use a more specific exception class derived from it

            throw new ApplicationException(“Monkey exception”);

        }

        private void exceptionOnNewFormButton_Click(object sender, EventArgs e)

        {

            Form1 form = new Form1();

            form.Show();

        }

    }

}

 

4.  Replace the code in Form1.Designer.cs with the code below:

 

namespace ExceptionHandling1

{

    partial class Form1

    {

        /// <summary>

        /// Required designer variable.

        /// </summary>

        private System.ComponentModel.IContainer components = null;

        /// <summary>

        /// Clean up any resources being used.

        /// </summary>

        /// <param name=”disposing”>true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing && (components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }

        #region Windows Form Designer generated code

        /// <summary>

        /// Required method for Designer support – do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {

            this.throwExceptionButton = new System.Windows.Forms.Button();

            this.newFormButton = new System.Windows.Forms.Button();

            this.SuspendLayout();

            //

            // throwExceptionButton

            //

            this.throwExceptionButton.Location = new System.Drawing.Point(12, 12);

            this.throwExceptionButton.Name = “throwExceptionButton”;

            this.throwExceptionButton.Size = new System.Drawing.Size(75, 51);

            this.throwExceptionButton.TabIndex = 0;

            this.throwExceptionButton.Text = “Throw Exception”;

            this.throwExceptionButton.UseVisualStyleBackColor = true;

            this.throwExceptionButton.Click += new System.EventHandler(this.throwExceptionButton_Click);

            //

            // newFormButton

            //

            this.newFormButton.Location = new System.Drawing.Point(93, 12);

            this.newFormButton.Name = “newFormButton”;

            this.newFormButton.Size = new System.Drawing.Size(75, 51);

            this.newFormButton.TabIndex = 2;

            this.newFormButton.Text = “New Form”;

            this.newFormButton.UseVisualStyleBackColor = true;

            this.newFormButton.Click += new System.EventHandler(this.exceptionOnNewFormButton_Click);

            //

            // ExceptionHandlingForm

            //

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(202, 79);

            this.Controls.Add(this.newFormButton);

            this.Controls.Add(this.throwExceptionButton);

            this.Name = “ExceptionHandlingForm”;

            this.Text = “Exception Handling”;

            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button throwExceptionButton;

        private System.Windows.Forms.Button newFormButton;

    }

}

 

5.  Run this code.  If you run the code in debug, when you hit the ‘Throw Exception’ button the code will break saying that an exception has occurred (unless you’ve disabled this).  If you now hit F5 to continue you will see that the top-level exception handler is being called.  If you run the code by double-clicking ExceptionHandling1.exe you will see that the top-level exception handler has been called directly.

Advertisements

3 thoughts on “Top-level Exception Handling in Windows Forms Applications – Code Listing 1

  1. Hey Amey
    this is absolutely fantastic code…Much more easy,small n important thing is you have explained it very well 🙂

    Really useful….God Bless You

    Thanks Friend
    DD the Day Dreamer

    🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s