小编ami*_*ngh的帖子

析构函数C++中的异常

我很清楚,不应该在析构函数中抛出任何异常.

但作为掌握这一概念的一部分,我编写了这个例子: -

#include <iostream>
using namespace std;

class A {
private: 
    int i;

public:
    A()
    {
        i = 10;
    }
    ~A()
    {
        throw 30;
    }
};
int main(){
    try{
        A();
        throw 10;
    }
    catch (int i){
        cout << i << endl;
        cout << "exception caught" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,这个程序应该通过调用std :: terminate()来终止,因为同时会有两个例外.但是,这个程序给出了以下输出: -

30
exception caught
Run Code Online (Sandbox Code Playgroud)

任何人都可以向我解释这背后的逻辑,为什么这不是终止?

c++ destructor exception-handling

36
推荐指数
2
解决办法
6043
查看次数

标签 统计

c++ ×1

destructor ×1

exception-handling ×1