繁体   English   中英

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

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

我似乎无法从C ++构造函数中为堆栈上实例化的对象引发异常(与使用new关键字分配的动态对象相反)。 如何完成的?

#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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM