如何从成员析构函数中捕获异常
How to catch exception from member destructor
我想知道是否(以及如何)捕获成员析构函数中抛出的异常。示例:
#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?
}
};
是的,您可以使用 function-try-block:
捕获此类异常
class B
{
A _a;
public:
~B() try {
// destructor body
}
catch (const std::exception& e)
{
// do (limited) stuff
}
};
但是,对于这样的异常,您实际上无能为力。该标准指定您不能访问 B
对象的非静态数据成员或基础 类。
此外,您不能 使异常静音。与其他函数不同,一旦析构函数(或构造函数)的 function-try-block 处理程序完成执行,异常将被隐式重新抛出。
总而言之,析构函数真的不应该抛出异常。
这是一个不言自明的示例,您可以做什么:
#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 The currently handled exception is rethrown if control reaches the
end of a handler of the function-try-block of a constructor or
destructor.
我想知道是否(以及如何)捕获成员析构函数中抛出的异常。示例:
#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?
}
};
是的,您可以使用 function-try-block:
捕获此类异常class B
{
A _a;
public:
~B() try {
// destructor body
}
catch (const std::exception& e)
{
// do (limited) stuff
}
};
但是,对于这样的异常,您实际上无能为力。该标准指定您不能访问 B
对象的非静态数据成员或基础 类。
此外,您不能 使异常静音。与其他函数不同,一旦析构函数(或构造函数)的 function-try-block 处理程序完成执行,异常将被隐式重新抛出。
总而言之,析构函数真的不应该抛出异常。
这是一个不言自明的示例,您可以做什么:
#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 The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.