SlideShare a Scribd company logo
1 of 6
Download to read offline
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

What's hot

14 exception handling
14 exception handling14 exception handling
14 exception handling
jigeno
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++
Prof Ansari
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception handler
Exception handler Exception handler
Exception handler
dishni
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Alpesh Oza
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Sharda
 

What's hot (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++
 

Similar to Exception Handling in the C++ Constructor

C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
Srikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
Srikanth
 
Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1
guest739536
 
C++tutorial
C++tutorialC++tutorial
C++tutorial
dips17
 

Similar to 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
 

More from Somenath Mukhopadhyay

More from 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
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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