
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Exception handling and object destruction in C++
Destructors in C++ basically called when objects will get destroyed and release memory from the system. When an exception is thrown in the class, the destructor is called automatically before the catch block gets executed.
Algorithm
Begin Declare a class sample1. Declare a constructor of sample1. Print “Construct an Object of sample1” Declare a destructor of sample1. Print “Destruct an Object 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 Code
#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; } }
Output
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
- Related Articles
- Exception handling in PowerShell
- Exception Handling Basics in C++
- Comparison of Exception Handling in C++ and Java
- Exception Handling in C++ vs Java
- What is exception handling in Python?
- What is exception handling in C#?
- What is Exception Handling in PHP ?
- NodeJS - Exception Handling in Asynchronous Code
- NodeJS - Exception Handling in eventful Code
- NodeJS - Exception Handling in Synchronous Code
- PHP Exception Handling with finally
- C# Exception Handling Best Practices
- Handling Exception and use of CX_ROOT directly and subclasses
- Exception handling with method overriding in Java.
- Importance of Proper Exception Handling in Java

Advertisements