What happens when exception thrown in constructor?

Share the Article

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

Main Funda: The exception called from constructor means the object is partially constructed, the compiler cannot guarantee a partial destruction in such cases

Related Topics:

Why a destructor should never throw exception?
What is the problem with setjmp( ) & longjmp( ) ?
Basics of throwing and catching exception
Why should we catch an exception object, using reference-parameter?
What happens when exception thrown from a constructor?
Re-throwing an exception
What are function level try-catch blocks
Understanding exception specification for functions
Explaining C++ casts
How pointer to class members are different ?
What is reference collapsing?
How to make a class object un-copyable?

Share the Article

Leave a Reply

Your email address will not be published. Required fields are marked *