C# Quirks - finalizer is called if constructor throws an exception, but it is NOT called if method throws an exception

Edit: Make sure to read the comment by Kevin Thompson

Test it out like this

     class Foo
    {
        public Foo(bool throwException)
        {
            if (throwException)
            {
                throw new InvalidOperationException();
            }
        }

        ~Foo() { Console.WriteLine("destructor called"); }

        public void Test() { throw new InvalidOperationException(); }
    }

class Program
    {
        static void Test1()
        {
            Console.WriteLine("running Test1");
            Foo obj;
            try
            {
                obj = new Foo(true);    // ctor will throw exception
            }
            catch
            {
            }
            GC.Collect(); // destructor will be called
        }

        static void Test2()
        {
            Console.WriteLine("running Test2");
            Foo obj = new Foo(false);    // no exception in ctor
            try
            {
                obj.Test();    // exception in method
            }
            catch { }
            GC.Collect();    // destructor will NOT be called
        }

        static void Main(string[] args)
        {
            // Test1();
            Test2();            
            Console.WriteLine("done");
            Console.ReadLine();
        }
    }

This makes sense, because if an exception occurs in the constructor, then this means the object has not been constructed.
Finally, remember that in C++, destructor is automatically called whenever an exception occurs

Comments

  • Anonymous
    April 15, 2013
    The comment has been removed