/*
Prevent Exceptions from Leaving Destructors
*/
class dog
{
public:
string m_name;
dog(string name)
{
m_name = name;
cout << name << "is born." << endl;
}
~dog()
{
cout << m_name << "is distroied." << endl;
throw 20;
}
void bark() {...}
};
int main()
{
try
{
dog dog1("Henry");
dog dog2("Bob");
//throw 20;
dog1.bark();
dog2.bark();
}
catch (int e)
{
cout << e << "is caught" << endl;
}
}
/*
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." << endl;
}
void prepareToDestr()
{
...; throw 20;
}
void bark() {...}
};
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;
}
}