AppDomain.UnhandledException Part 1

Mon, December 20, 2004, 03:49 PM under MobileAndEmbedded
The punchline is that the AppDomain class (along with other enhancements such as AppDomain.Unload), also offers AppDomain.CurrentDomain.UnhandledException. As soon as I saw that (in combination with this), I started running various tests (over 20 different combination scenarios run in release mode with no debugger attached) in order to update an older post on Global Exception Handling on the CF 2.0.

Let's remember that unhandled exception tests must include: Throwing on the GUI, on a ThreadPool thread, Thread, Control.Invoke, object finalizer and after Application.Run when the app is exiting. As you recall, on the desktop the only way to cater for all of these is by hooking into AppDomain.UnhandledException, Application.ThreadException and surround Application.Run with try..catch. CF 1.0's limitation was fully described here.

With NETCF 2.0, we still don't have Application.ThreadException but, unlike the desktop scenario, we don't need it since the NETCF 2.0 AppDomain.UnhandledException catches *all* unhandled exceptions. Here is an example of its use:

static class EntryPoint {
[MTAThread]
static void Main() {
// Add Global Exception Handler
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(OnUnhandledException);

Application.Run(new Form1());
}

// In CF case only, ALL unhandled exceptions come here
private static void OnUnhandledException(Object sender,
UnhandledExceptionEventArgs e) {
Exception ex = e.ExceptionObject as Exception;
if (ex != null) {
// Can't imagine e.IsTerminating ever being false
// or e.ExceptionObject not being an Exception
SomeClass.SomeStaticHandlingMethod(ex, e.IsTerminating);
}
}
}


Note that I have never seen e.IsTerminating be false, in other words after your handler gets run the process exits. The last statement includes the case where you throw an exception in the handler; so, exceptions thrown in the global exception handling routine are swallowed (why would you throw in there in the first place is a valid question).

Next entry will serve as a holder of the VB equivalent code plus a blurb on try..catch around Application.Run. Go :-)

I stripped this article from the fine detail and instead just presented the result; if you have a deeper interest let me know and I'll send you how I arrived at the conclusions.
Comments are closed.