SlideShare a Scribd company logo
SOM-ITSOLUTIONS
C++
Exception Handling at C++ Constructor
SOMENATH MUKHOPADHYAY
som-itsolutions
#A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282
Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com
Website:​ ​http://www.som-itsolutions.com/
Blog: ​www.som-itsolutions.blogspot.com
Its a very common problem in C++ that if a class's constructor throws an exception (say
memory allocation exception) how we should handle it. Think about the following piece of code.
CASE I:
class A{
private: int i;
//if exception is thrown in the constructor of A, i will de destroyed by stack unwinding
//and the thrown exception will be caught
A()
{
i = 10;
throw MyException(“Exception thrown in constructor of A()”);
}
};
void main(){
try{
A();
}
catch(MyException& e){
e.printerrmsg();
}
}
Here class A's constructor has thrown an exception.. so the best way to handle such situation is
to instantiate A inside a try block...if exception is thrown in the constructor of A, i will be
destroyed by stack unwinding and the thrown exception will be caught... try​catch block in
exception is very important as constructor cannot return anything to indicate to the caller that
something wrong has happened...
CASE II
Lets consider the following case.
class A{
private:
char* str1;
char* str2;
A()
{
str1 = new char[100];
str2 = new char[100];
}
}
Here in class A we have two dynamically allocated char array. Now suppose while constructing
A, the system was able to successfully construct the first char array, i.e. str1. However, while
allocating the memory of str2, it throws OutOfMemory exception. As we know the destructor of
an object will be called only if the object is fully constructed. But in this case the object is not
fully constructed. Hence even if we release the memory in the destructor of A, it will never be
called in this case. So what we will have is that the stack based pointers, i.e. str1 and str2 will
be deleted because of stack unwinding. If you can’t understand the previous line, here is what
happened when we allocate a memory in heap. Look at the following diagram. This is what
happened when we write ​char* ptr = new char[100];
It means that the ptr itself is on the stack while the memory that it is pointing to is in the heap.
So the memory that have been allocated in the Heap won’t be destroyed. Hence we will have
two blocks of heap memory ( one for the str1 that is 100 bytes long and the other for whatever
have been allocated by str2 before the exception being thrown) which are not referenced by any
pointer (str1 and str2 which have already been destroyed by the stack unwinding). Hence it is a
case of memory leak.
Now the question is how can we handle the above situation. We can do it as follows.
class A{
private:
char* str1;
char* str2;
A()
{
try{
str1 = new char[100];
}
catch (...){
delete[] str1;
throw(); //rethrow exception
}
try{
str2 = new char[100];
}
catch(...){
delete[] str1;
delete[] str2;
throw(); //rethrow exception
}
But the best way to handle this kind of situation in modern C++ is to use auto_ptr/shared_ptr.
Look at the following piece of code to know how we have used boost’s shared pointer to avoid
memory leaks in the C++ constructor.
#include <iostream>
#include <string>
#include <memory>
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
using namespace std;
class SomeClass{
public:
SomeClass(){}
~SomeClass(){};
};
typedef boost::shared_ptr<SomeClass> pSomeClass;
typedef boost::shared_ptr<cha> pChar;
typedef boost::shared_array<char> pBuffer;
class MyException{
public:
MyException(string str){
msg = str;
}
void printerrmsg(){
cout<<msg.c_str<<endl;
}
private:
string msg;
};
class A{
private:
int i;
pChar m_ptrChar;
pSomeClass m_ptrSomeClass;
pBuffer m_pCharBuffer;
public:
A():m_ptrChar(new char),m_ptrSomeClass(new SomeClass),m_pCharBuffer(new
char[100])
{
i = 10;
throw MyException("Exception at A's constructor");
}
};
In Symbian C++, it is handled by a concept called two phase constructor... (it came into the
picture because there was no template concept in earlier Symbian C++, and hence there was
no auto_ptr)... in this process, if we want to create a dynamic memory allocation at the heap
pointed by say *pMem, then in the first phase of construction we initialize the object pointed by
pMem;. obviously this cannot throw exception... We then push this pMem to the cleanup stack...
and in the second phase of construction, we allocate memory pointed by pMem... so, if the
constructor fails while allocating memory, we still have a reference of pMem in the cleanup
stack... we just need to pop it and destroy it... hence there is no chance of memory leak...
EXCEPTION CLASS
#include <iostream>
#include <string>
#include <memory>
class MyException(string str){
private:
string msg;
public:
MyException(string str){
msg = str;
}
void printerrmsg(){
cout<<msg.c_str()<<endl;
}
}

More Related Content

PPT
Exception handling and templates
PPT
Handling Exceptions In C &amp; C++[Part A]
PPTX
exception handling in cpp
PPT
Exception handling
PPTX
Exception handling chapter15
PPTX
Exception Handling in C++
PPTX
Exception handling c++
PPT
Exceptions in c++
Exception handling and templates
Handling Exceptions In C &amp; C++[Part A]
exception handling in cpp
Exception handling
Exception handling chapter15
Exception Handling in C++
Exception handling c++
Exceptions in c++

What's hot (20)

PPT
Exception handling
PPTX
C++ ala
PDF
14 exception handling
PDF
Exception handling
PPTX
Exception Handling in object oriented programming using C++
PDF
C++ exception handling
PPTX
Exception handling
PDF
EXCEPTION HANDLING in C++
PPS
Exception handling in c programming
PPT
Week7 exception handling
PPT
Exception handling
PPT
Exception handler
PPSX
Exception Handling
PDF
Exception Handling
PPTX
What is Exception Handling?
PDF
Exception handling
PPT
Unit iii
PPT
Exception Handling in JAVA
PPTX
Exception handling in java
PPTX
Exception handling in c++
Exception handling
C++ ala
14 exception handling
Exception handling
Exception Handling in object oriented programming using C++
C++ exception handling
Exception handling
EXCEPTION HANDLING in C++
Exception handling in c programming
Week7 exception handling
Exception handling
Exception handler
Exception Handling
Exception Handling
What is Exception Handling?
Exception handling
Unit iii
Exception Handling in JAVA
Exception handling in java
Exception handling in c++
Ad

Similar to Exception Handling in the C++ Constructor (20)

PDF
Safe Clearing of Private Data
PPTX
6-Exception Handling and Templates.pptx
TXT
Advance C++notes
PPTX
Namespaces
PDF
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
PPTX
Smart pointers
PPTX
C++ memory leak detection
PPTX
(Slightly) Smarter Smart Pointers
PPTX
How to Adopt Modern C++17 into Your C++ Code
PPTX
How to Adopt Modern C++17 into Your C++ Code
PDF
Cpp17 and Beyond
DOC
C - aptitude3
DOC
C aptitude questions
PDF
(3) cpp abstractions more_on_user_defined_types
PDF
Checking the Open-Source Multi Theft Auto Game
PDF
(5) cpp dynamic memory_arrays_and_c-strings
PPT
Exception Handling1
ODP
Chapter03
PPT
Lecture5
PPT
C++tutorial
Safe Clearing of Private Data
6-Exception Handling and Templates.pptx
Advance C++notes
Namespaces
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
Smart pointers
C++ memory leak detection
(Slightly) Smarter Smart Pointers
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Cpp17 and Beyond
C - aptitude3
C aptitude questions
(3) cpp abstractions more_on_user_defined_types
Checking the Open-Source Multi Theft Auto Game
(5) cpp dynamic memory_arrays_and_c-strings
Exception Handling1
Chapter03
Lecture5
C++tutorial
Ad

More from Somenath Mukhopadhyay (20)

PDF
Significance of private inheritance in C++...
PDF
Arranging the words of a text lexicographically trie
PDF
Generic asynchronous HTTP utility for android
PDF
Copy on write
PDF
Java concurrency model - The Future Task
PDF
Memory layout in C++ vis a-vis polymorphism and padding bits
PDF
Developing an Android REST client to determine POI using asynctask and integr...
PDF
Observer pattern
PDF
Uml training
PDF
How to create your own background for google docs
PDF
The Designing of a Software System from scratch with the help of OOAD & UML -...
PDF
Structural Relationship between Content Resolver and Content Provider of Andr...
PDF
Flow of events during Media Player creation in Android
PDF
Implementation of a state machine for a longrunning background task in androi...
PDF
Tackling circular dependency in Java
PDF
Implementation of composite design pattern in android view and widgets
PDF
Active object of Symbian in the lights of client server architecture
PDF
Android services internals
PDF
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
PDF
Composite Pattern
Significance of private inheritance in C++...
Arranging the words of a text lexicographically trie
Generic asynchronous HTTP utility for android
Copy on write
Java concurrency model - The Future Task
Memory layout in C++ vis a-vis polymorphism and padding bits
Developing an Android REST client to determine POI using asynctask and integr...
Observer pattern
Uml training
How to create your own background for google docs
The Designing of a Software System from scratch with the help of OOAD & UML -...
Structural Relationship between Content Resolver and Content Provider of Andr...
Flow of events during Media Player creation in Android
Implementation of a state machine for a longrunning background task in androi...
Tackling circular dependency in Java
Implementation of composite design pattern in android view and widgets
Active object of Symbian in the lights of client server architecture
Android services internals
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Composite Pattern

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Electronic commerce courselecture one. Pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
The Rise and Fall of 3GPP – Time for a Sabbatical?
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
20250228 LYD VKU AI Blended-Learning.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Programs and apps: productivity, graphics, security and other tools
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Electronic commerce courselecture one. Pdf
The AUB Centre for AI in Media Proposal.docx
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Exception Handling in the C++ Constructor

  • 1. SOM-ITSOLUTIONS C++ Exception Handling at C++ Constructor SOMENATH MUKHOPADHYAY som-itsolutions #A2 1/13 South Purbachal Hospital Road Kolkata 700078 Mob: +91 9748185282 Email: ​som@som-itsolutions.com​ / ​som.mukhopadhyay@gmail.com Website:​ ​http://www.som-itsolutions.com/ Blog: ​www.som-itsolutions.blogspot.com
  • 2. Its a very common problem in C++ that if a class's constructor throws an exception (say memory allocation exception) how we should handle it. Think about the following piece of code. CASE I: class A{ private: int i; //if exception is thrown in the constructor of A, i will de destroyed by stack unwinding //and the thrown exception will be caught A() { i = 10; throw MyException(“Exception thrown in constructor of A()”); } }; void main(){ try{ A(); } catch(MyException& e){ e.printerrmsg(); } } Here class A's constructor has thrown an exception.. so the best way to handle such situation is to instantiate A inside a try block...if exception is thrown in the constructor of A, i will be destroyed by stack unwinding and the thrown exception will be caught... try​catch block in exception is very important as constructor cannot return anything to indicate to the caller that something wrong has happened... CASE II Lets consider the following case. class A{ private: char* str1; char* str2; A() { str1 = new char[100]; str2 = new char[100]; } }
  • 3. Here in class A we have two dynamically allocated char array. Now suppose while constructing A, the system was able to successfully construct the first char array, i.e. str1. However, while allocating the memory of str2, it throws OutOfMemory exception. As we know the destructor of an object will be called only if the object is fully constructed. But in this case the object is not fully constructed. Hence even if we release the memory in the destructor of A, it will never be called in this case. So what we will have is that the stack based pointers, i.e. str1 and str2 will be deleted because of stack unwinding. If you can’t understand the previous line, here is what happened when we allocate a memory in heap. Look at the following diagram. This is what happened when we write ​char* ptr = new char[100]; It means that the ptr itself is on the stack while the memory that it is pointing to is in the heap. So the memory that have been allocated in the Heap won’t be destroyed. Hence we will have two blocks of heap memory ( one for the str1 that is 100 bytes long and the other for whatever have been allocated by str2 before the exception being thrown) which are not referenced by any pointer (str1 and str2 which have already been destroyed by the stack unwinding). Hence it is a case of memory leak. Now the question is how can we handle the above situation. We can do it as follows. class A{ private: char* str1; char* str2; A() { try{
  • 4. str1 = new char[100]; } catch (...){ delete[] str1; throw(); //rethrow exception } try{ str2 = new char[100]; } catch(...){ delete[] str1; delete[] str2; throw(); //rethrow exception } But the best way to handle this kind of situation in modern C++ is to use auto_ptr/shared_ptr. Look at the following piece of code to know how we have used boost’s shared pointer to avoid memory leaks in the C++ constructor. #include <iostream> #include <string> #include <memory> #include <boost/shared_ptr.hpp> #include <boost/shared_array.hpp> using namespace std; class SomeClass{ public: SomeClass(){} ~SomeClass(){}; }; typedef boost::shared_ptr<SomeClass> pSomeClass; typedef boost::shared_ptr<cha> pChar; typedef boost::shared_array<char> pBuffer; class MyException{ public: MyException(string str){ msg = str; } void printerrmsg(){ cout<<msg.c_str<<endl; }
  • 5. private: string msg; }; class A{ private: int i; pChar m_ptrChar; pSomeClass m_ptrSomeClass; pBuffer m_pCharBuffer; public: A():m_ptrChar(new char),m_ptrSomeClass(new SomeClass),m_pCharBuffer(new char[100]) { i = 10; throw MyException("Exception at A's constructor"); } }; In Symbian C++, it is handled by a concept called two phase constructor... (it came into the picture because there was no template concept in earlier Symbian C++, and hence there was no auto_ptr)... in this process, if we want to create a dynamic memory allocation at the heap pointed by say *pMem, then in the first phase of construction we initialize the object pointed by pMem;. obviously this cannot throw exception... We then push this pMem to the cleanup stack... and in the second phase of construction, we allocate memory pointed by pMem... so, if the constructor fails while allocating memory, we still have a reference of pMem in the cleanup stack... we just need to pop it and destroy it... hence there is no chance of memory leak...
  • 6. EXCEPTION CLASS #include <iostream> #include <string> #include <memory> class MyException(string str){ private: string msg; public: MyException(string str){ msg = str; } void printerrmsg(){ cout<<msg.c_str()<<endl; } }