C++ - 捕获双重异常

C++ - catching a double exception

我有以下代码:

#include <iostream>
using namespace std;

class A {
public:
    A()  { cout << "A::A()" << endl;}
    ~A() { cout << "A::~A()" << endl; throw "A::exception";}
};

class B {
public:
    B()  { cout << "B::B()" << endl; throw "B::exception";}
    ~B() { cout << "B::~B()";}
};

int main() {
    try {
        cout << "Entering try...catch block" << endl;
        A   objectA;
        B   objectB;
        cout << "Exiting try...catch block" << endl;
    } catch (char const * ex) {
        cout << ex << endl;
    }
    return 0;
}

现在,在提出问题之前,我想指出这段代码是不好的做法(例如,从构造函数中抛出异常将导致对象未完全创建,因此不会调用析构函数并且它可能会导致内存泄漏或其他问题)。

现在,主要的顺序是这样的:

  1. 打印"Entering try...catch block".

  2. 调用A的构造函数,打印"A::A()"

  3. 调用B的构造函数,打印"B::B()",并抛出异常。

  4. 异常被抛出,"Exiting try...catch block"行不会被打印。该块已退出,因此调用了 A 的析构函数。

  5. A 的析构函数打印 "A::~A()" 并抛出另一个异常。

第二个异常(在 5 中)导致 main 在进入 catch 块之前抛出异常。

我的问题是 - 有没有办法在不改变 类 A,B?

的情况下捕获主要的第二个异常

我试图用另一个 try-catch 块包围整个 try-catch 块和 catch 块内部,但这没有用。

谢谢。

来自cppreference.com

As any other function, a destructor may terminate by throwing an exception [...] however if this destructor happens to be called during stack unwinding, std::terminate is called instead.

因此,从 ~A() 抛出异常的尝试不会导致抛出第二个异常;它导致程序被终止。如果你需要 "catch" 这个 "second exception",你就需要干扰 the termination handler。或者您可以找到一种不在析构函数中抛出异常的方法。从 cppreference.com 继续:

Although std::uncaught_exception may sometimes be used to detect stack unwinding in progress, it is generally considered bad practice to allow any destructor to terminate by throwing an exception.