从静态[非动态]对象的c++构造函数抛出异常

Throwing an exception from C++ constructor for static [non-dynamic] objects

本文关键字:c++ 构造函数 抛出异常 对象 静态 动态      更新时间:2023-10-16

对于在堆栈上实例化的对象(与用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;
}

你需要重新构建你的代码:

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
}