When dog objects in main() go out of scope, it invokes destructor. Since destructor throws an exception, due to multiple exception condition program crashes.
public:
string m_name;
dog(string name)
{
m_name = name;
cout << name << " is born." << endl;
}
~dog()
{
cout << m_name << " is distroied.\n" << endl;
throw 10;
}
};
int main()
{
try {
dog dog1("Henry");
dog dog2("Bob");
}
catch (int e) {
cout << e << " is caught" << endl;
}
return 1;
}
Solution 1: Destructor swallow the exception
~dog() {
try {
// Enclose all the exception prone code here
} catch (MYEXCEPTION e) {
// Catch exception
} catch (...) {
}
}
Solution 2: Move the exception-prone code to a different function
class dog {
public:
string m_name;
dog(string name) {m_name = name; cout << name << " is born." << endl; }
~dog() { cout<< m_name << " is distroied.\n" << endl; }
void prepareToDestr() { throw 20; }
void bark() {cout<< m_name << " 's dog is barking.\n" << endl; }
};
int main{} {
try {
dog dog1("Henry");
dog dog2("Bob");
dog1.bark();
dog2.bark();
dog1.prepareToDestr();
dog2.prepareToDestr();
} catch (int e) {
cout << e << " is caught" << endl; // Only Exception of dog1 is caught
}
}
Note: Destructor in main
class dog {
public:
string m_name;
dog(string name) {m_name = name; cout << name << " is born." << endl; }
~dog() { cout<< m_name << " is destroyed.\n" << endl; }
void bark() {cout<< m_name << " 's dog is barking.\n" << endl; } // It never gets invokes
};
int main{} {
try {
dog dog1("Henry");
dog dog2("Bob");
throw 20;
dog1.bark();
dog2.bark();
} catch (int e) {
cout << e << " is caught" << endl; // Exception of dog1 is caught
}
}
Output:
Henry is born.
Bob is born.
Bob is distroied.
Henry is distroied.
20 is caught
Comments
Post a Comment