析构函数中抛出异常¶
ID: cpp/throw-in-destructor
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- reliability
- readability
- language-features
Query suites:
- cpp-security-and-quality.qls
此规则查找析构函数中抛出的异常。这样做很危险:如果析构函数在堆栈展开期间被调用(作为处理其他异常的一部分),根据 C++ 规范,抛出额外的异常将立即终止程序。
建议¶
以其他方式处理错误条件。
示例¶
class C {
public:
//...
~C(){
if (error) {
throw "Exception in destructor"; //wrong: exception thrown in destructor
}
}
};
void f() {
C* c = new C();
try {
doOperation(c);
delete c;
} catch ( char * do_operation_exception) {
delete c; //would immediately terminate program if C::~C throws an exception
}
}
参考资料¶
M. Cline, C++ 常见问题解答:如何处理失败的析构函数?
B. Stroustrup. _The C++ Programming Language Special Edition_ p 380. Addison Wesley. 2000.