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


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 */

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

5/23/2017 12:25:31 PM

Accepted Answer

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.

11/20/2008 5:33:20 PM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow