c++ - 从对象内部返回值给 main

标签 c++ object error-handling

在我的 main() 中,我正在创建在构造函数中进行错误检查的对象。 如果发生错误,我想从 main() 返回错误代码以退出程序。

我应该在 main() 中使用回调来返回错误代码,还是不应该在构造函数中进行错误检查;将其移动到可以向 main() 返回错误代码的成员函数?

最佳答案

你可以为此使用throw:

struct C
{
    C() {throw std::runtime_error("for the example");}
};


int main()
{
    try
    {
        C c;

        // Do normal stuff (that never happen due to throw)
        return 0;
    }
    catch (const std::exception& e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }
}

关于c++ - 从对象内部返回值给 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038787/

相关文章:

c++ - 在执行过程中将 callgrind/valgrind 附加到程序

c++ - 为什么将枚举声明标记为 const?

JavaScript 容纳字符串、对象和数组

node.js - 请求超时时,nodejs http.request关闭过程

java - 增加堆栈跟踪中显示的行数

c++ - 计算存在的 shared_ptr 数

c++ - 将 unsigned char * 数组可视化为位图

javascript - 仅克隆具有少量属性的对象

python - Python中的实例和对象有什么区别?

node.js - 如何从错误对象获取错误状态代码