下面是这节说的导致程序terminate
异常情况的demo:
// exceptions
#include <iostream>
using namespace std;
class Session {
public:
Session() {
logCreation(this);
}
~Session() {
logDestruction(this);//an uncaught exception occurs
}
private:
static void logCreation(Session *objAddr) {
cout << "Create " << objAddr << '\n';
}
static void logDestruction(Session *objAddr) {
cout << "Destroy " << objAddr << '\n';
cout << "Throw an exception in" << objAddr << '\n';
throw 21;
}
};
void on_terminate(){
cout << "terminate function called!" << endl;
return;
}
void test() {
Session s;
try {
throw 20;
} catch (int e) {
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
}
int main () {
set_terminate(on_terminate);
test();
cout<<"terminate function not called!"<<endl;
return 0;
}
main
函数中首先抛出了异常,导致Session
对象析构,logDestruction
被调用,抛出异常21,而析构函数没有捕获这个异常,而是让它流出了destructor
以外,而此时异常20正在作用,C++会调用terminate
函数,程序终止:
Create 0x7646678d3c4d
An exception occurred. Exception Nr. 20
Destroy 0x7646678d3c4d
Throw an exception in0x7646678d3c4d
terminate function called!
如果在析构函数中try-catch
:
~Session() {
try {
logDestruction(this);
} catch (int e) {
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
}
则程序正常执行完毕:
Create 0x7cae77ecf33d
An exception occurred. Exception Nr. 20
Destroy 0x7cae77ecf33d
Throw an exception in0x7cae77ecf33d
An exception occurred. Exception Nr. 21
terminate function not called!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。