C#/.NET trick for catching exceptions

Here’s an interesting little tip for anyone who’s writing a C# and/or any .NET application.

I’ve been writing/maintaining a relatively large application used by many different users, and have discovered many bugs that can come up over hours and hours of use. Well, us programmers are all just human, and don’t always write bulletproof code, especially when that code is run by 10’s or 100’s of different people. Most of the time when something bad happens, an exception is thrown by the application. If this exception goes unhandled, the program just crashes. It would be kinda handy sometimes to be able to catch each and every one of these unhandled exceptions, and at the very least log the problem and gracefully exit the program.

This is pretty trivial to do in any .NET application, and for an example using C#:

  1. Application.ThreadException += new ThreadExceptionEventHandler( OnThreadException );
  2. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  3. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( UnUnhandledException );

The first line adds an event handler to the ThreadException event, which will be fired every time an unhandled exception happens inside the main UI thread of the application. So, if you have, say, 2 separate components to your application running on 2 different threads ( the main UI thread…Windows forms stuff, and a processing backend), you could gracefully shut down and restart the UI.

For the 2nd line, this tells the application to handle all exceptions, regardless of what the user has set in the application settings. This is directly then made use of in the next line, where we add an event handler to the UnhandledException event on the Current Application Domain. This way, any other unhandled exceptions from any other threads that are running in your application will be caught and this event will be fired with all the information you need. In my case, I gather up the exception details, allow the user to enter a description of what they were doing, and send an email to myself with all these details.

The one catch when dealing with unhandled exceptions is that once they occur, even if you catch them with this method, you won’t be able to recover from the crash. The programs is going to exit, regardless. But, like I said, at the very least you can log the error in some way, so you can figure out what went wrong and prevent it from crashing again.

I just figured this might help any potential .NET developers out there. I pulled most of this from Microsoft’s MSDN site here.

Until next time…