How to catch ALL exceptions/crashes in a .NET app [duplicate]

Possible Duplicate:
.NET - What’s the best way to implement a “catch all exceptions handler”

I have a .NET console app app that is crashing and displaying a message to the user. All of my code is in a try{<code>} catch(Exception e){<stuff>} block, but still errors are occasionally displayed.

In a Win32 app, you can capture all possible exceptions/crashes by installing various exception handlers:

/* C++ exc handlers */
_set_se_translator
SetUnhandledExceptionFilter
_set_purecall_handler
set_terminate
set_unexpected
_set_invalid_parameter_handler

What is the equivalent in the .NET world so I can handle/log/quiet all possible error cases?


Solution 1:

You can add an event handler to AppDomain.UnhandledException event, and it'll be called when a exception is thrown and not caught.

Solution 2:

Contrary to what some others have posted, there's nothing wrong catching all exceptions. The important thing is to handle them all appropriately. If you have a stack overflow or out of memory condition, the app should shut down for them. Also, keep in mind that OOM conditions can prevent your exception handler from running correctly. For example, if your exception handler displays a dialog with the exception message, if you're out of memory, there may not be enough left for the dialog display. Best to log it and shut down immediately.

As others mentioned, there are the UnhandledException and ThreadException events that you can handle to collection exceptions that might otherwise get missed. Then simply throw an exception handler around your main loop (assuming a winforms app).

Also, you should be aware that OutOfMemoryExceptions aren't always thrown for out of memory conditions. An OOM condition can trigger all sorts of exceptions, in your code, or in the framework, that don't necessarily have anything to do with the fact that the real underlying condition is out of memory. I've frequently seen InvalidOperationException or ArgumentException when the underlying cause is actually out of memory.

Solution 3:

This article in codeproject by our host Jeff Atwood is what you need. Includes the code to catch unhandled exceptions and best pratices for showing information about the crash to the user.

Solution 4:

The Global.asax class is your last line of defense. Look at:

protected void Application_Error(Object sender, EventArgs e)

method

Solution 5:

Be aware that some exception are dangerous to catch - or mostly uncatchable,

  • OutOfMemoryException: anything you do in the catch handler might allocate memory (in the managed or unmanaged side of the CLR) and thus trigger another OOM
  • StackOverflowException: depending whether the CLR detected it sufficiently early, you might get notified. Worst case scenario, it simply kills the process.