...
A destructor should perform the same way whether or not there is an active exception. Typically, this means that it should invoke only operations that do not throw exceptions, or it should handle all exceptions and not rethrow them (even implicitly). This compliant solution differs from the previous noncompliant code example by having an explicit return
statement in the SomeClass
destructor. This statement prevents control from reaching the end of the error exception handler. Consequently this Consequently, this handler will catch the exception thrown by Bad::~Bad()
when bad_member
is destroyed, and it will also catch any exceptions thrown within the compound statement of the function-try-block, but the SomeClass
destructor will not terminate by throwing an exception.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdexcept> class SomeClass { class Bad { bool has_error() const; public: ~Bad() noexcept(false) { if (has_error()) { throw std::logic_error("Something bad"); } } } bad_member; public: ~SomeClass() try { // ... } catch(...) { // Catch exceptions thrown from noncompliant destructors of // member objects or base class subobjects. // NOTE: Flowing off the end of a destructor function-try-block causes // the caught exception to be implicitly rethrown, but an explicit // return statement will prevent that from happening. return; } }; |
...