How to overcome StackOverflowException bypassing unhandled exception handling in .NET

There are three kind of so-called “asynchronous exceptions”. That are the ThreadAbortException, the OutOfMemoryException and the mentioned StackOverflowException. Those excepions are allowed to occur at any instruction in your code.

And, there’s also a way to overcome them:

The easiest is the ThreadAbortException. When the current code executes in a finally-block. ThreadAbortExceptions are kind of “moved” to the end of the finally-block. So everything in a finally-block can’t be aborted by a ThreadAbortException.

To avoid an OutOfMemoryException, you have only one possibility: Do not allocate anything on the Heap. This means that you’re not allowed to create any new reference-types.

To overcome the StackOverflowException, you need some help from the Framework. This help manifests in Constrained Execution Regions. The required stack is allocated before the actual code is executed and additionally also ensures that the code is already JIT-Compiled and therefor is available for execution.

There are three forms to execute code in Constrained Execution Regions (copied from the BCL Team Blog):

  • ExecuteCodeWithGuaranteedCleanup, a stack-overflow safe form of a try/finally.
  • A try/finally block preceded immediately by a call to RuntimeHelpers.PrepareConstrainedRegions. The try block is not constrained, but all catch, finally, and fault blocks for that try are.
  • As a critical finalizer – any subclass of CriticalFinalizerObject has a finalizer that is eagerly prepared before an instance of the object is allocated.
    • A special case is SafeHandle’s ReleaseHandle method, a virtual method that is eagerly prepared before the subclass is allocated, and called from SafeHandle’s critical finalizer.

You can find more at these blog posts:

Constrained Execution Regions and other errata [Brian Grunkemeyer] at the BCL Team Blog.

Joe Duffy’s Weblog about Atomicity and asynchronous exception failures where he gives a very good overview over asynchronous exceptions and robustness in the .net Framework.

Leave a Comment