Exception Handling and Object Destruction in C++
An exception is termed as an unwanted error that arises during the runtime of the program. The practice of separating the anomaly-causing program/code from the rest of the program/code is known as Exception Handling.
An object is termed as an instance of the class which has the same name as that of the class. A destructor is a member function of a class that has the same name as that of the class but is preceded by a ‘~’ (tilde) sign, also it is automatically called after the scope of the code runs out. The practice of pulverizing or demolition of the existing object memory is termed object destruction.
In other words, the class of the program never holds any kind of memory or storage, it is the object which holds the memory or storage and to deallocate/destroy the memory of created object we use destructors.
Constructing an object of class Test Destructing the object of class Test Caught 10
When an exception is thrown, destructors of the objects (whose scope ends with the try block) are automatically called before the catch block gets executed. That is why the above program prints “Destructing an object of Test” before “Caught 10“.
What Happens When an Exception is Thrown From a Constructor?
Constructing an Object of class Test1 Constructing an Object of class Test2 Destructing an Object the class Test1 Caught 20
Destructors are only called for the completely constructed objects. When the constructor of an object throws an exception, the destructor for that object is not called.
Predict the output of the following program:
Constructing object number 1 Constructing object number 2 Constructing object number 3 Constructing object number 4 Destructing object number 3 Destructing object number 2 Destructing object number 1 Caught 4