Exception Handling and Object Destruction in C++

About Exception handling and object destruction :

Exception handling and objection destruction are important features in c++ to handle properly for execution of the program. We will discuss about these below.

Exception Handling in C++

Exception Handling in C++ :

Object Destruction in C++:

Example 1 :

Run
#include<iostream>
using namespace std;
class check {
public:
	check()
	{
		cout << "Constructing an object of class check "<< endl;
	}

	~check()
	{
		cout << "Destructing the object of class check "<< endl;
	}
};
int main()
{
	try {
		check t1;
		throw 5;
	}
	catch (int i) {
		cout << "Caught " << i << endl;
	}
}

Output :

Constructing an object of class check 
Destructing the object of class check 
Caught 5


In the above program, 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.

Example 2:

Run
#include<iostream>
using namespace std;

class check1 {
public:
	check1()
	{
		cout << "Constructing an Object of class check1"<< endl;
	}
	~check1()
	{
		cout << "Destructing an Object the class check1"<< endl;
	}
};

class check2 {
public:
	check2() 
	{
		cout << "Constructing an Object of class check2"<< endl;
		throw 5;
	}
	~check2()
	{
		cout << "Destructing the Object of class check2"<< endl;
	}
};

int main()
{
	try {
		check1 t1;
		check2 t2;
		check1 t3; 
	}
	catch (int i) {
		cout << "Caught " << i << endl;
	}
}

Output :

Constructing an Object of class check1
Constructing an Object of class check2
Destructing an Object the class check1
Caught 5

In the above program,exception is thrown from the constructor. Here  the destructor for that object is not called, When the constructor of an object throws an exception.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription