The exceptions are thrown by functions to ensure that unexpected scenario encountered are gracefully handled by catch blocks. The exception handling mechanism in these catch blocks also takes care to destroy all existing objects. The compiler destroys these objects by calling their destructor.
Exception thrown in Constructor
Constructors are special type functions and they are exception to this rule of exceptions. When a constructor of class throws an exception, then corresponding destructor will not be called. This means, if constructor has allocated heap memory or has opened handle to resources, these will never be deallocated.
C++ Compiler, do not consider an object as complete, if its constructor throws and exception. The compiler will not call destructor in such cases.
#include <iostream> //main header
using namespace std; //for namespace
class MainFunda
{
public:
MainFunda(int throwexception=0)
{
cout << "MainFunda()" << endl;
if(throwexception) throw 1;
}
~MainFunda()
{
cout << "~MainFunda()" << endl;
}
};
int main()
{
try
{
MainFunda a1; //destructor will be called
MainFunda a2; //destructor will be called
MainFunda a3(1); //destructor will not get called
MainFunda a4;
}
catch (int x)
{
cout << "Inside catch" << endl;
}
return 0;
}
The output is:
MainFunda()
MainFunda()
MainFunda()
~MainFunda()
~MainFunda()
Inside catch