Skip to main content

C# Tutorial - Dealing With Unhandled Exceptions [Beginner]


It's a fact of life that all applications have bugs- even after strenuous bench testing, automated testing, and piles and piles of test plans. When you release software into the wild, something is going to go wrong, somewhere. So it is nice to have an underlying architecture in your program so that when something does go horribly, unavoidably wrong, there is at least some record of what happened - so you can start tracking down and reproducing it. Today we are going to talk about an extremely simple way to do just that in C#.

Generally, since we are in the managed world of .NET and C#, when something horrible goes wrong with your program, it will eventually manifest itself as an unhandled exception - and then the app will crash and burn. Now, I suppose you could try and surround all your code with generic try-catch statements, but (I'm hoping) we all know that that is just a horrible idea, from performance, maintenance, and code readability perspectives. Fortunately, there is a better way to implement that idea in .NET - the UnhandledException event.

The UnhandledException is an event on the AppDomain class. An AppDomain is, in very simplistic terms, the execution environment for your code. We are going to assume today that there is only one AppDomain, and we aren't going to worry about it any more than that. Talking about AppDomains could probably take an entire tutorial in and of itself. But anyway, we have this event - what does it do and how do we attach to it?

What it does is pretty simple - the event is fired every time there is an unhandled exception that propagates all the way to the top of your application. Now, if there was nothing attached to the event, the app would show one of those classic "this app has encountered a problem and needs to close" dialogs, and down your app would go. But once you attach to this event, you have a chance to do something.

How to attach to the event is a little weird - but only in that you may have never added code to this part of a C# app before - especially if what you mostly work with are GUI apps. We need to add a line to the Main method (by default in the "Program.cs" file in a new Windows Application):
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MyApp
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      AppDomain.CurrentDomain.UnhandledException += 
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }
  }
}
 
That is the content of a default "Program.cs" file for a new Visual Studio Windows Application called "MyApp" - with one difference. The line of code AppDomain.CurrentDomain.Unhandled... is what I added in order to attach to the UnhandledException event of my AppDomain. Of course, here it is referencing a function that does not yet exist (CurrentDomain_UnhandledException) - but we will get to that next.

Ok, lets write that method:
static void CurrentDomain_UnhandledException
  (object sender, UnhandledExceptionEventArgs e)
{
  try
  {
    Exception ex = (Exception)e.ExceptionObject;

    MessageBox.Show("Whoops! Please contact the developers with the following" 
          + " information:\n\n" + ex.Message + ex.StackTrace, 
          "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  }
  finally
  {
    Application.Exit();
  }
}
 
And there you go - now your unhandled exceptions are being shown in a nice happy dialog! Of course, you could do other things here - like log the exception, or try and soften the blow of the crash by saving whatever program state you can. You can't, however, actually keep the program from crashing - there is no way to "catch" the exception at this point and let the app keep on running.

But wait, there's more! As I stated before, with the UnhandledException event on AppDomain, any exception in the current AppDomain will trigger that event. This includes not only the main application thread (the UI thread), but any other threads as well. And, as I just mentioned, there is no way to "recover" once you hit that point. However, there is actually a different way to handle unhandled exceptions on the Application thread (i.e., the thread that is handling your UI - forms, painting/ user input, etc..). This is through the ThreadException event on Application. To do this, we add another line to the main method:
Application.ThreadException += 
  new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
 
And we define the function Application_ThreadException:
public static void Application_ThreadException
  (object sender, System.Threading.ThreadExceptionEventArgs e)
{
  DialogResult result = DialogResult.Abort;
  try
  {
    result = MessageBox.Show("Whoops! Please contact the developers with the" 
      + " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace, 
      "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
  }
  finally
  {
    if (result == DialogResult.Abort)
    {
      Application.Exit();
    }
  }
}
 
With this method hooked to the Application.ThreadException, unhandled exceptions on the main application thread will not hit the UnhandledException event on the AppDomain - and the app will no longer terminate by default. As you can see in this method, we show a dialog asking if the user wants to continue or not - and if they choose abort, we close the app. Otherwise, we just let the app continue on.

Here is what the file "Program.cs" looks like now:
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MyApp
{
  static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      AppDomain.CurrentDomain.UnhandledException +=
        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
      Application.ThreadException += 
        new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
    }

    static void CurrentDomain_UnhandledException
        (object sender, UnhandledExceptionEventArgs e)
    {
      try
      {
        Exception ex = (Exception)e.ExceptionObject;

        MessageBox.Show("Whoops! Please contact the developers with "
           + "the following information:\n\n" + ex.Message + ex.StackTrace, 
           "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
      }
      finally
      {
        Application.Exit();
      }
    }

    public static void Application_ThreadException
      (object sender, System.Threading.ThreadExceptionEventArgs e)
    {
      DialogResult result = DialogResult.Abort;
      try
      {
        result = MessageBox.Show("Whoops! Please contact the developers "
          + "with the following information:\n\n" + e.Exception.Message 
          + e.Exception.StackTrace, "Application Error", 
          MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
      }
      finally
      {
        if (result == DialogResult.Abort)
        {
          Application.Exit();
        }
      }
    }
  }
}
 
In any decent sized application, the code in either of these two methods would probably be much more complicated - logging much more state information, trying to determine if the app could continue at all, so on and so forth. But hopefully this gives you an idea of where to put that sort of logic in a C# application.

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# Snippet - The Many Uses Of The Using Keyword [Beginner]

What is the first thing that pops into your mind when you think of the using keyword for C#? Probably those lines that always appear at the top of C# code files - the lines that import types from other namespaces into your code. But while that is the most common use of the using keyword, it is not the only one. Today we are going to take a look at the different uses of the using keyword and what they are useful for. The Using Directive There are two main categories of use for the using keyword - as a "Using Directive" and as a "Using Statement". The lines at the top of a C# file are directives, but that is not the only place they can go. They can also go inside of a namespace block, but they have to be before any other elements declared in the namespace (i.e., you can't add a using statement after a class declaration). Namespace Importing This is by far the most common use of the keyword - it is rare that you see a C# file that does not h

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as