Exception thrown in destructor¶
ID: cpp/throw-in-destructorKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - reliability - readability - language-featuresQuery suites: - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
This rule finds exceptions thrown in destructors. This is dangerous: If the destructor is called during stack unwinding as part of the handling of another exception, throwing an additional exception will immediately terminate the program as per the C++ specification.
Recommendation¶
Handle the error condition in a different way.
Example¶
classC{public://...~C(){if(error){throw"Exception in destructor";//wrong: exception thrown in destructor}}};voidf(){C*c=newC();try{doOperation(c);deletec;}catch(char*do_operation_exception){deletec;//would immediately terminate program if C::~C throws an exception}}
References¶
B. Stroustrup.The C++ Programming Language Special Edition p 380. Addison Wesley. 2000.