我想知道是否(以及如何)可以捕获成员析构函数中抛出的异常。例子:
#include <exception>
class A
{
public:
~A() {
throw std::exception("I give up!");
}
};
class B
{
A _a;
public:
~B() {
// How to catch exceptions from member destructors?
}
};
我想知道是否(以及如何)可以捕获成员析构函数中抛出的异常。例子:
#include <exception>
class A
{
public:
~A() {
throw std::exception("I give up!");
}
};
class B
{
A _a;
public:
~B() {
// How to catch exceptions from member destructors?
}
};
是的,您可以使用函数-try-block 捕获这样的异常:
class B
{
A _a;
public:
~B() try {
// destructor body
}
catch (const std::exception& e)
{
// do (limited) stuff
}
};
但是,对于这样的异常,您真的不能做太多事情。该标准规定您不能访问对象的非静态数据成员或基类B
。
此外,您不能使异常静音。与其他函数不同,一旦析构函数(或构造函数)的函数尝试块处理程序完成执行,异常将被隐式重新抛出。
总而言之,析构函数真的不应该抛出异常。
这是一个不言自明的示例,您可以做什么:
#include <stdexcept>
#include <iostream>
class A
{
public:
~A() noexcept(false) {
throw std::runtime_error("I give up!");
}
};
class B
{
A _a;
public:
~B() noexcept(false) try {
// dtor body
}
catch (std::exception const& e)
{
std::cout << "~B: " << e.what() << std::endl;
// rethrown and you can't do anything about it
}
};
int main()
{
try
{
B b;
}
catch (std::exception const& e)
{
std::cout << "main: " << e.what() << std::endl;
}
}
我相信,对 C++ 标准的正确引用(我使用 n3376 的副本)在15.3 处理异常中:
15 如果控制到达构造函数或析构函数的函数try块的处理程序的末尾,则重新抛出当前处理的异常。