Exception Handling and Object Destruction in C++



In this article, you will learn what is exception handling, object destruction, and Handing exception thrown in Object Destructor in C++.

C++ Exception Handling

An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.

  • try: This block contains the code (program) that may generate an exception.
  • throw: This keyword throws an exception if occurred during the code execution written in try block.
  • catch: The catch block contains the code to handle the exception.

Syntax for the exception handling

Following is the syntax for the Exception Handling in C++:

try {
    // Code that might throw an exception
} catch (exception_type1 e1) {
    // Handle exception of type1
} catch (exception_type2 e2) {
    // Handle exception of type2
}

Example of Exception Handling

The program checks for division by zero and if it is found, it throws and catches an error message instead of crashing:

#include<iostream>
using namespace std;
int main() {
   try{
      int a = 10, b = 0;
      if (b == 0)
         throw "Division by zero!";  
      //Throws a string exception
      int result = a / b;
      cout<<"Result: "<<result<<endl;
   } catch (const char* msg) {
       // Catches the exception and shows message
       cout<<"Error: "<<msg<<endl;  
   } 
   return 0;
}

Following is the output to the above program:

Error: Division by zero!

C++ Object Destructor

A destructor is a member function in a class that is called when an object goes out of scope or it is deleted.

~ is a tilde symbol that is placed before the class name to define a destructor.

Syntax to create a destructor

Following is the syntax to create destructor in C++.

~ClassName() {
    // Cleanup code here
}

Example of Desctrutor

The program creates an object of a class by calling a function to display a message, and cleans up the object using the destructor:

#include<iostream>
using namespace std;
class MyClass {
public:
   MyClass() {
      cout<<"Constructor called\n";
   }
    void displayMessage() {
      cout<<"Hello from MyClass object!\n";
   } 
   ~MyClass() {
      cout<<"Destructor called\n";
   }
};

int main() {
   // Constructor is called here
   MyClass obj;  
   // Call a member function
     obj.displayMessage();  
   return 0;  
}

Following is the output to the above program:

Constructor called
Hello from MyClass object!
Destructor called

Handing Exception Thrown in Object Destructor

Destructors is called when objects will get destroyed and release memory from the system. When an exception is thrown in the class, the destructor is called before the catch block and gets executed automatically.

Algorithm

Following is the algorithm is as follows.

Begin
   Declare a class sample1.
      Declare a constructor of sample1.
         Print "Construct an Object of sample1"
      Declare a destructor of sample1.
   Declare a class sample.
      Declare a constructor of sample2.
         Declare variable i of the integer datatype.
         Initialize i = 7.
         Print "Construct an Object of sample1".
         Throw i.
      Declare a destructor of sample2.
         Print "Destruct an Object of sample2"
   Try:
      Declare an object s1 of class sample1.
      Declare an object s2 of class sample2.
   Ctach(int i)
      Print "Caught".
      Print the value of variable i.
End.

Example

In C++, a constructor runs when an object is created. But if something goes wrong, it can throw an exception. If the object is not created and its destructor is not called. So, the constructor throws an exception. However, destructors will clean up memory of previously created objects.

In this program, when 'Sample2' throws an exception during construction, only Sample1 destructor is called because the object is created before the error.

#include<iostream>
using namespace std;
class Sample1 {
   public:
      Sample1() {
         cout<<"Construct an Object of sample1"<<endl;
      }
      ~Sample1() {
         cout<<"Destruct an Object of sample1"<<endl;
      }
};
class Sample2 {
   public:
      Sample2() {
         int i =7;
         cout<<"Construct an Object of sample2"<<endl;
         throw i;
      }
      ~Sample2() {
         cout<<"Destruct an Object of sample2"<<endl;
      }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
      cout<<"Caught "<<i<<endl;
   }
}

Following is the output to the above program:

Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-06-10T13:11:44+05:30

835 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements