如何从成员析构函数中捕获异常 [英] How to catch exception from member destructor

查看:86
本文介绍了如何从成员析构函数中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否(以及如何)捕获在成员析构函数中引发的异常。示例:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆