【问题标题】:Throwing an exception from C++ constructor for static [non-dynamic] objects从 C++ 构造函数中为静态 [非动态] 对象抛出异常
【发布时间】:2023-04-01 10:55:01
【问题描述】:

对于在堆栈上实例化的对象(与使用 new 关键字分配的动态对象相反),我似乎无法从 C++ 构造函数中抛出异常。这是如何实现的?

#include <stdexcept>

class AClass
{
public:
    AClass() 
    {
        throw std::exception();
    }

    void method() { }
};

int main(void)
{
    try { AClass obj; } // obj is only valid in the scope of the try block
    catch (std::exception& e)
    {

    }

    obj.method(); // obj is no longer valid - out of scope

    return 0;
}

【问题讨论】:

  • 抱歉,您的问题具体是什么?您的代码清楚地显示了堆栈上的对象在构造过程中如何抛出,这就是您要问的。
  • 你不能。如果异常从构造函数中传播出来,则意味着构造函数失败。如果构造函数失败,你就没有对象。
  • 如果你想在对象构建后使用它,请将使用该对象的代码放在 try 块中。毕竟,它的运行能力取决于没有发生异常。
  • try { AClass obj; obj.method(); }
  • 顺便说一句,“静态”对象与您的问题不同。

标签: c++ exception constructor


【解决方案1】:

你需要稍微重构一下你的代码:

int main(void)
{
    try { 
        AClass obj; 
        obj.method();
    } // obj is only valid in the scope of the try block
    catch (std::exception& e)
    {

    }
}

如果您需要将“无法创建 AClass 对象”的异常与其他异常分开捕获,则针对该情况抛出一个唯一异常,并为该类型的异常添加特定的 catch 子句:

class no_create : public std::runtime_error { 
    // ...
};

try {
     AClass obj;
     obj.method();
}
catch (no_create const &e) { 
    std::cerr << e.what() << "\n";
}
catch (std::exception const &e) { 
    //  process other exceptions
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2019-03-11
    • 2023-03-11
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多