c++ - 异常处理,c++中的意外终止符

标签 c++ exception terminate

以下代码是关于异常处理的。我得到了输出:

Botch::f()
I'll be back!

为什么没有抓到水果?谢谢!

忽略这个。我想我已经提供了足够的细节。

#include <exception>
#include <iostream>
using namespace std;

void terminator() {
    cout << "I'll be back!" << endl;
    exit(0);
}

void (*old_terminate)() = set_terminate(terminator);

class Fruit {};

class Botch {
public:
    void f() throw(Fruit, bad_exception) {
        cout << "Botch::f()" << endl;
        throw Fruit();
    }
    ~Botch() { throw 'c'; }
};

int main() {
    try{
        Botch b;
        b.f();
    } catch(Fruit&) {
        cout << "inside catch(Fruit)" << endl;
    } catch(bad_exception&) {
        cout << "caught a bad_excpetionfrom f" << endl;
    }
}

最佳答案

因为在 Fruit 异常的堆栈展开期间,您抛出了另一个异常(来自 Botch 析构函数)。所以你的终结者被调用了。这就是为什么从析构函数中抛出异常不是一个好主意,

关于c++ - 异常处理,c++中的意外终止符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16037929/

相关文章:

c++ - 仅当某些值在 C++ 中保持不变时才读取某些列

c++ - 为什么 g++5 在自动类型推导中推导对象而不是 initializer_list

go - 如何编写 “exception oriented”代码而不是 “if-error oriented”代码?

java.sql.SQLException : Io exception: Socket read timed out vs Closed Connection 异常

c++ - 当可以返回错误/异常时,从库中终止调用程序(例如,调用 exit())总是错误的吗?

c++ - 创建/加入线程时的隐式同步

python - CPPYY/CTYPES 将字符串数组作为 char* args[] 传递

java - 如何在日志文件中显示异常原因的详细信息

c - 如何使用 while 循环终止程序

c++ - 在 ' '(空格)字符后终止输入