Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')
Yes, destructors are guaranteed to be called on stack unwinding, including unwinding due to exception being thrown. There are only few tricks with exceptions that you have to remember: Destructor of the class is not called if exception is thrown in its constructor.
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
C++ : Yes and No. While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.
When you throw from the constructor, it will call the destructor of any object constructed so far: the member variables and the inherited classes (section 15.2/2). If you call the destructor manually, their destructor will be also called (section 12.4/8).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With