如何从成员析构函数中捕获异常 [英] How to catch exception from member destructor
问题描述
我想知道是否(以及如何)捕获在成员析构函数中引发的异常。示例:
I wonder whether (and how) it's possible to catch an exception thrown in a member destructor. Example:
#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
对象的非静态数据成员或基类。
However, you cannot really do much with such an exception. The standard specifies that you cannot access non-static data members or base classes of the B
object.
此外,您无法将异常静音。与其他函数不同,一旦析构函数(或构造函数)的 function-try-block 处理程序执行完毕,该隐式将隐式重新抛出。
Also, you cannot silence the exception. Unlike with other functions, the exception will be re-thrown implicitly once the function-try-block handler of a destructor (or constructor) finishes execution.
总而言之,析构函数实际上不应引发异常。
All in all, destructors should really not throw exceptions.
这篇关于如何从成员析构函数中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!