SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
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;
}
}

Contenu connexe

Tendances

Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
C++ exception handling
C++ exception handlingC++ exception handling
C++ exception handlingRay Song
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++Prof Ansari
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programmingRaza Najam
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Exception handler
Exception handler Exception handler
Exception handler dishni
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 

Tendances (20)

Exception handling
Exception handlingException handling
Exception handling
 
C++ ala
C++ alaC++ ala
C++ ala
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
C++ exception handling
C++ exception handlingC++ exception handling
C++ exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programming
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handler
Exception handler Exception handler
Exception handler
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handlingException handling
Exception handling
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 

Similaire à Exception Handling in the C++ Constructor

Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private DataPVS-Studio
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptxSatyamMishra237306
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...ScyllaDB
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detectionVõ Hòa
 
(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart Pointers(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart PointersCarlo Pescio
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_typesNico Ludwig
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameAndrey Karpov
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
 
Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1guest739536
 
C++tutorial
C++tutorialC++tutorial
C++tutorialdips17
 

Similaire à Exception Handling in the C++ Constructor (20)

Safe Clearing of Private Data
Safe Clearing of Private DataSafe Clearing of Private Data
Safe Clearing of Private Data
 
6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
Namespaces
NamespacesNamespaces
Namespaces
 
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
ceph::errorator<> throw/catch-free, compile time-checked exceptions for seast...
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detection
 
(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart Pointers(Slightly) Smarter Smart Pointers
(Slightly) Smarter Smart Pointers
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
 
Checking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto GameChecking the Open-Source Multi Theft Auto Game
Checking the Open-Source Multi Theft Auto Game
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
 
Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1
 
Chapter03
Chapter03Chapter03
Chapter03
 
Lecture5
Lecture5Lecture5
Lecture5
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
 

Plus de Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trieSomenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidSomenath Mukhopadhyay
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsSomenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docsSomenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidSomenath Mukhopadhyay
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in JavaSomenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsSomenath Mukhopadhyay
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureSomenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternSomenath Mukhopadhyay
 

Plus de Somenath Mukhopadhyay (20)

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

Dernier

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 

Dernier (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 

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; } }