Item 08-Don't let exception escape destructor (Prevent exceptions from leaving destructors)
C + + does not prohibit the destructor from spitting out the exception, but it does not encourage you to do so. There is a reason for that.
Ex:
Class widget{
Public
~widget () {...} Suppose this might spit out an anomaly.
};
void DoSomething ()
{
Std::vector<widget> v;
...//v here to destroy
}
When Vector v is destroyed, it is the responsibility to destroy all the widgets that it contains, assuming that V contains multiple widgets, during which the program may end prematurely or appear ambiguous as long as the destructor spits out the exception.
Workaround:
Ex:
Class dbconn{
Public
~dbconn ()
{
Db.close ();
}
Private
DBConnection DB;
}
If the close call causes an exception, the Dbconn destructor propagates the exception
Workaround:
1. End the program if close throws an exception, usually by calling abort
Dbconn::~dbconn ()
{
Try{db.close;}
catch (...)
{
Make the operation record, write down the call to close failed;
Std::abort ();
}
}
2. Swallow the exception that occurred because of the call to close
Dbconn::~dbconn ()
{
Try{db.close ();}
catch (...)
{
Make a running record and write down the call to close failed
}
}
Better strategy: Redesign the Dbconn interface to give its customers the opportunity to respond to potential problems.
Please remember:
Destructors never spit out an exception; If a function called by a destructor might throw an exception, the destructor should catch any exceptions and swallow them (not propagate) or end the program.
If a customer needs to react to an exception thrown during the operation of an action function, then class should provide a normal function (rather than a destructor) to execute.
Effective C + + Item 08-Don't let exceptions escape destructors