Is the destructor called if the constructor throws an exception?

Qwertie picture Qwertie · Oct 9, 2008 · Viewed 12k times · Source

Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')

Answer

Jon Skeet picture Jon Skeet · Oct 9, 2008

It does for C# (see code below) but not for C++.

using System;

class Test
{
    Test()
    {
        throw new Exception();
    }

    ~Test()
    {
        Console.WriteLine("Finalized");
    }

    static void Main()
    {
        try
        {
            new Test();
        }
        catch {}
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

This prints "Finalized"