Avoid “program stopped working” in C#/.NET

The JIT debugger popup occurs when there’s an unhandled exception. That is, an exception tunnels all the way up the stack to the root of any thread in the runtime.

To avoid this, you can handle the AppDomain.CurrentDomain.UnhandledException event and just call Environment.Exit(1) to exit gracefully.

This will handle all exceptions on all threads within your AppDomain. Unless you’re doing anything special, your app probably only has one AppDomain, so putting this in your public static void Main method should suffice:

AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
    Console.Error.WriteLine("Unhandled exception: " + args.ExceptionObject);
    Environment.Exit(1);
};

You should probably use the NAnt logger to write out the error in this case too (can’t recall the API for this offhand though.)

You can also disable JIT debugging on the machine. I would only recommend this in certain circumstances such as for a dedicated build server.

Leave a Comment