'How to overcome StackOverflowException bypassing unhandled exception handling in .NET

After hitting a few StackOverflowExceptions in .NET I noticed they completely bypass the unhandled exception handlers that .NET offers (Application.ThreadException / AppDomain.UnhandledException). This is very disturbing since we have critical cleanup code in those exception handlers.

Is there any way to overcome this?



Solution 1:[1]

Not really; a stack overflow (or "out of memory") exception happens within the CLR itself means something has gone critically wrong (I usually get it when I've been dumb and created a recursive property).

When this state occurs there is no way for the CLR to allocate new function calls or memory to enable it to call into the exception handlers; it's a "we must halt now" scenario.

If, however, you throw the exception yourself, your exception handlers will be called.

Solution 2:[2]

A stackoverflow isn't something you can just recover from, since it can't allocate more stack memory to even call your exception handler.

The only thing you can really do is track down the cause and prevent it from happening at all (eg becareful with recursion, and don't allocate large objects on the stack).

Solution 3:[3]

blowdart nailed it. Really just a problem with typing code too quickly.

private Thing _myThing = null;

Public Thing MyThing
{
   get{
        return this.MyThing;}
   set{
        this.MyThing = value;}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TylerH
Solution 2 Fire Lancer
Solution 3 BSMP