title: Why ExecuteCodeWithGuaranteedCleanup doesn't work?
body: <p>I was trying to "measure" stack depth. Why the following program doesn't print anything?</p>
  
  <pre><code>class Program
  {
      private static int Depth = 0;
  
      static void A(object o) 
      {
          Depth++;
          A(o);
      }
  
      static void B(object o, bool e)
      {
          Console.WriteLine(Depth);
      }
  
      static void Main(string[] args)
      {
          RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(A, B, null);
      }
  }
  </code></pre>
  
  <p>Some answers simply include a quote from MSDN, like "Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default." Believe me, sometimes (when there is enough stack space) it can be cought, the following prints some number just fine:</p>
  
  <pre><code>class Program
  {
      private static int depth = 0;
  
      static void A(object o)
      {
          depth++;
          if (Environment.StackTrace.Length &gt; 8000)
              throw new StackOverflowException("Catch me if you can.");
          A(o);
      }
  
      static void B(object o, bool e)
      {
          Console.WriteLine(depth);
      }
  
      static void Main(string[] args)
      {
          RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(A, B, null);
      }
  }
  </code></pre>