In this article, we will learn how to handle an unhandled exception being thrown in C#. An exception is an error that occurs at runtime, and an unhandled exception occurs when the application fails to handle the exception being thrown properly.

Unhandled Exceptions in C# Applications

The UnhandledException Event notifies an app whenever an unhandled exception occurs in the default application domain. If an exception is not handled by the try/catch block, it will go unhandled and needs an event handler.

For example, if the Windows Runtime invokes app code that throws an exception and doesn’t catch it, the exception will redirect control back to the Windows Runtime which then triggers the UnhandledException event to notify the application of this exception.

Now, go to the program C# file and add the event function below:

        static void ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
            
        }

Then add the delegate below to the Main() function in your program.cs file:

Application.ThreadException += new ThreadExceptionEventHandler(ThreadException);

The final version of the program.cs file will look like the following:

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

namespace myWinFormApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new ThreadExceptionEventHandler(ThreadException);
            Application.Run(new frmMain());
        }

        static void ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "Unhandled Exception");
        }


    }
}

Trigger the Unhandled Exception Event

Now let’s make up a bogus code that will throw a System.IndexOutOfRangeException exception.

        private void frmMain_Load(object sender, EventArgs e)
        {
            int[] arr = new int[1];
            for (int j = 0; j <= 2; j++)
            {
                arr[j] = 2;
            }
        }

As the code above was not wrapped by a try/catch block, the exception will be handled by the ThreadException function we just added to the program.cs file:

Customize the Error Message

You can, however, show the user a custom error message and log the error message in an error log, store it in a database, or send it via email to the responsible parties(such as application administrator or developer)

        static void ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            MessageBox.Show("An error has occurred. Please contact you system administrator", "Error Occurred");
            // Here you can log the error in an error log, database, or send the error InnerException and/or StackTrace to an administrator via email or 
        
        }

Related Articles

Last modified: September 11, 2019

Comments

Write a Reply or Comment

Your email address will not be published.