2

Please note this code:

 class CTestFinally
  {
      public static void Run()
      {
          try
          {
              TryAndTry();
          }
          catch (Exception exError)
          {
              Console.WriteLine(exError.Message);
          }
          finally
          {
              Console.WriteLine("Finally...!");
          }
          Console.ReadKey();
      }

      static void TryAndTry()
      {
          try
          {
              TryAndTry();
          }
          catch (Exception exError)
          {
              Console.WriteLine(exError.Message);
          }
          finally
          {
              Console.WriteLine("Try: Finally...!");
          }
          }
}
      }

Finally never executed because we get stack overflow Error.

Are there any circumstances under which the finally block does not get executed other than above problem?

2 Answers2

5

StackOverflowException is one of the few kinds of exception that a CLR host typically treats specially. ASP.NET will kill the worker process for example. This is very hard to debug because your app just goes away. SQL Server has similar policies I'm sure (like unloading the appdomain).

The reason for that is that this is a destabilizing condition that does not allow for reliable error recovery (after all your stack is unusable! You can for example not call your logger or send an email. There is no room on the stack.).

Another of this kind is OutOfMemoryException (you can't even allocate an Exception - that's why the CLR pre-allocates one OOM instance...). I think ASP.NET tolerates this while SQL Server kills your appdomain.

For normal exceptions this works fine.

usr
  • 168,620
  • 35
  • 240
  • 369
2

This will never execute the finally:

using System;

namespace Demo
{
    public static class Program
    {
        [STAThread]
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("In try");
                Environment.FailFast("Aaaaaargh");
            }

            finally
            {
                Console.WriteLine("In finally");
            }
        }
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276