I have the following code:
#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;
}
在提出问题之前,我想指出这段代码是不好的实践(例如从构造函数抛出异常会导致对象没有完全创建,因此析构函数不会被调用,可能会导致内存泄漏或其他问题)。
现在,主要过程的顺序如下:
打印
"进入 try...catch 块"
。调用
A
的构造函数,打印"A::A()"
。调用
B
的构造函数,打印"B::B()"
,并抛出异常。抛出异常,行
"退出 try...catch 块"
将不会被打印。块已退出,因此调用A
的析构函数。A
的析构函数打印"A::~A()"
并抛出另一个异常。
第二个异常(在5中)会导致主程序抛出异常,然后进入 catch
块。
我的问题是 - 是否有办法在不更改类 A
、B
的情况下,在主程序中捕获第二个异常?
我尝试在整个 try-catch
块和 catch
块内部周围包裹另一个 try-catch
块,但没有奏效。
谢谢。
try {B objectB;} catch(...){}
并单独捕获该异常。虽然有一定用处。 - Bo Persson