Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Basics of Object-Oriented Programming in C++
3.
Exception Handling On Destructors
3.1.
Example Code:
3.1.1.
Output
3.1.2.
Explanation: 
4.
Exception inside Constructors
4.1.
Example Code:
4.1.1.
Output:
4.1.2.
Explanation:
5.
Frequently Asked Questions
5.1.
What is the purpose of using a destructor in C++?
5.2.
Does the C++ compiler create a default constructor when we write our own?
5.3.
What is the order of constructor execution in C++?
6.
Conclusion
Last Updated: Mar 27, 2024

Exception Handling and Object Destruction

Author Akash Nagpal
0 upvote

Introduction

This article will have an overview of C++ objects and destructors. Later on, we will discuss one of the essential and most asked topics, i.e. how the exceptions are handled using constructors. 

Exception handling in C++ is vital because it helps to preserve the program's usual, desired flow even when unexpected occurrences occur. Programs may crash or requests may fail if exceptions are not handled appropriately. Customers may become irritated as a result, and a company's reputation may suffer as a result.

Here in this article, initially, we will have a revision on some basic topics of C++ related to OOPs. Later on, we learn about object destruction and exception handling in detail with the help of examples.

Also see, Literals in C.Fibonacci Series in C++

Basics of Object-Oriented Programming in C++

Before starting, let's have a peek at C++ objects, constructors & destructors, and exceptions:

  • C++ object: An instance of the class with the same name as the class is an object.
  • Constructor: A constructor is a member function that is automatically called when an object is formed. A constructor in C++ has the same name as the class and does not have a return type.
  • Destructor: A destructor is a member function of a class with the same name as the class but preceded by a (tilde “~” ) symbol. It is also called automatically when the scope of the code expires. Object destruction is the activity of crushing or destroying existing object memory.
  • C++ Exception: A C++ exception reacts to an unusual situation that occurs while a code is running, such as attempting to divide by zero. Exceptions allow us to move control from one portion of a program to another. Exception handling in C++ is based on three keywords: trycatch, and throw.

Note: A code in C++ never retains any form of memory or storage. It is the object that contains the memory or storage, and destructors are used to deallocate/destroy the memory of the produced object.

Exception Handling On Destructors

We will learn this concept with the help of an example given below:

Example Code:

#include <iostream> 
using namespace std; 
  
class Test { 
public: 
//Constructor
  Test() { cout << "Constructing an object of Test class" << endl; } 
//Destructor
  ~Test() { cout << "Destructing an object of Test class " << endl; } 
}; 
  
int main() { 
  try { 
    Test t1; 
//Throw passes an argument ot the exception handler. 
//Here int 10 is passed as an argument.
    throw 10; 
  } catch(int i) { 
    cout << "Caught " << i << endl; 
  } 
} 
You can also try this code with Online C++ Compiler
Run Code


Output

Constructing an object of Test class
Destructing an object of Test class 
Caught 10
You can also try this code with Online C++ Compiler
Run Code

Explanation: 

When an exception is thrown, the objects' destructors (whose scope ends with the try block) are automatically triggered before the catch block is performed. As a result, the preceding software outputs "Destructing an item of Test" before "Caught 10."

 

Exception inside Constructors

We will understand this concept with the help of the following example:

Example Code:

#include <iostream> 
using namespace std; 
  
class Test1 { 
public: 
  Test1() { cout << "Constructing an Object of Test1" << endl; } 
  ~Test1() { cout << "Destructing an Object of Test1" << endl; } 
}; 
  
class Test2 { 
public: 
  // Following constructor throws an integer exception 
  Test2() { cout << "Constructing an Object of Test2" << endl;  
            throw 20; } 
  ~Test2() { cout << "Destructing an Object of Test2" << endl; } 
}; 
  
int main() { 
  try { 
    Test1 t1; // Constructed and destructed 
    Test2 t2; // Partially constructed 
    Test1 t3; // t3 is not constructed as this statement never gets executed 
  } catch(int i) { 
    cout << "Caught " << i << endl; 
  } 
} 
You can also try this code with Online C++ Compiler
Run Code

Output:

Constructing an Object of Test1
Constructing an Object of Test2
Destructing an Object of Test1
Caught 20
You can also try this code with Online C++ Compiler
Run Code

Explanation:

Destructors are only invoked for properly developed constructed objects. When a function object throws an exception, the object's destructor is not invoked.

You practice by yourself with the help of online c++ compiler.

Must Read Dynamic Binding in C++

Frequently Asked Questions

What is the purpose of using a destructor in C++?

The primary function of the destructor is to release any resources (opened files, opened sockets, database connections, resource locks, and so on) allocated throughout the lifetime of your object.

Does the C++ compiler create a default constructor when we write our own?

In C++, the compiler builds a default constructor for each class by default. However, the compiler will not generate the default constructor if we specify our constructor.

What is the order of constructor execution in C++?

The base class constructor is run first, followed by the derived class constructor. Thus execution proceeds from top to bottom in the inheritance tree.

Conclusion

In this article, we have extensively discussed exceptional handling and object destruction in C++ with the help of various examples. We have also brushed up on some of the important C++ topics like C++ constructors, destructors, exceptions etc.  We hope this blog has helped you enhance your knowledge regarding the C++ concepts. Some official documentation on big data that can help you improve your understanding is this Pointer in C++ and Local class.

If you would like to learn more, check out our articles on Operator Keyword in C#cloud platform comparison, and 10 AWS best books.  Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass