SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Downloaden Sie, um offline zu lesen
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;
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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++
 

Ähnlich wie 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 aptitude questions
C aptitude questionsC aptitude questions
C aptitude questionsSrikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3Srikanth
 
(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
 

Ähnlich wie 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 aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
(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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

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