CRITICAL
Rule Definition
Destructors should be exception-safe. This is because a destructor will be automatically called when an exception is thrown to de-allocate all objects which are on the stack between the exception throw and catch. If a destructor ends up throwing an exception, either directly or indirectly, the program will terminate. The bottom line here: never allow an exception of any sort to be thrown from a destructor; the alternative opens up the possibility that a buggy program simply crashes without presenting any easily identifiable source for the bug.
Remediation
Remove the throw statements from destructors, prefer calling non throwing function only from destructors. If you call a potentially throwing function from a destructor, swallow all exception it may throw by wrapping it in a 'try/catch' clause.
If the object destruction can fail and you want to report it to the user, create a dedicated function that will be called separately before the destructor.
Violation Code Sample
Closing a file is an operation that may fail. Therefore, the standard library provides:
- A 'close' function, which the user can call explicitly and check the stream state afterwards,
- The destructor, which call the 'close' function if necessary but does not allow the user to check if it succeeded or failed. If the stream is configured to throw exceptions on error, those exceptions are swallowed by the destructor.
Reference
"How can I handle a destructor that fails?":http://www.parashift.com/c++-faq-lite/dtors-shouldnt-throw.html
Related Technologies
C++
Technical Criterion
Programming Practices - Error and Exception Handling
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.