Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the destructor called if the constructor throws an exception?

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

like image 459
Qwertie Avatar asked Oct 09 '08 19:10

Qwertie


People also ask

Is destructor called when exception is thrown?

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.

What happens if a constructor throws an exception?

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.

Is destructor run if constructor throws?

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.

Can we call destructor from constructor?

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).


1 Answers

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"

like image 193
Jon Skeet Avatar answered Sep 21 '22 06:09

Jon Skeet