CLOG

A coder's BLOG from Todd S. Murchison

Recent posts

Disclaimer

The opinions expressed herein are my own and do not represent any other individual or organization.

© Copyright 2010

Unhandled Exceptions. The first code you should always write...

You can find a large number of references on line talking about unhandled exceptions in the .NET Framework 2.0 and registering for the UnhandledException event. I would like to first, point out that this event is available in the Compact Framework 2.0 as well and second, recommend that the first thing you should do in any project is register for it.

In a standard Windows app the code would look something like this:

namespace YourNamespace {
    static class Program {
        [MTAThread]
        static void Main() {
            AppDomain.CurrentDomain.UnhandledException += 
                new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.Run(new YourAppForm());
        }
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            // Log the exception here
            MessageBox.Show(((Exception)e.ExceptionObject).Message, "ERROR");
        }
    }
}

In my opinion, it is a good idea to do this early on in a project (if not first thing). Eventually most projects of any size will end up with situations that muddle the normal chain of exception propagation. Dialog windows, multi-threaded behavior, exceptions not derived from Exception, or just "incorrect" code on your part are just a few things that can confuse exception cases. By handling the UnhandledException event you can guarantee that you maintain an iron grip on exception awareness and ensure that you are logging valuable failure information. As we all know "silent death" sucks.

-Todd

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by toddm on Monday, August 28, 2006 6:39 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Related posts

Comments are closed