c ++如何处理抛出异常的初始化程序

c++ how to handle initializer that throws exceptions

非常简单的问题,如何处理初始化可能从其构造函数中抛出异常的 class 成员变量?

class main
{
public:
    main() c(...) {};
private:
    my_class c;
};

class my_class
{
public:
    inline my_class() : o(...) { };

private:
    some_obj o;
};

显然您不能在构造函数初始值设定项中尝试捕获异常,那么在构造函数的 try catch 块中构造对象是否更合适?

这是顶级class,所以处理异常让用户知道发生了什么并优雅地退出比让程序因异常而崩溃更重要?

class main
{
public:
    main()
    {
        try
        {
            c(...);
        }
        catch(...)
        {
            ...
        }
    };
private:
    my_class c;
};

然而,这是行不通的,因为对象在构造函数中初始化之前先初始化一次,因此如果对象抛出异常,程序可能会崩溃。

为什么在构造函数中捕获不到错误?根据 this question 这似乎是标准做法。

你需要的是function-try-block。它专为解决您的问题而设计。

class main
{
public:
    main() try : c(...)
    {
        std::cout << "constructed, c = " << c << std::endl;
    }
    catch(...)
    {
        std::cerr << "failed to construct c = " << c << std::endl;
    } // implicit throw; here

private:
    my_class c;
};