【问题标题】:Unhandled exceptions - forcing program exit未处理的异常 - 强制程序退出
【发布时间】:2014-08-19 19:33:39
【问题描述】:

我有以下例子:

void Unhandled() {
    cout << "Unhandled exception!" << endl;
//  exit(-1);
}
int main(){
    float a, b;
    set_terminate(Unhandled);

    try{
        cout << "Input two numbers: ";
        cin >> a >> b;
        if (b == 0)
            throw "Division by zero!";
        cout << a / b;
    }
    catch (int n){
        cout << "Error ID: " << n << endl;
    }
    return 0;
}

我编写了这段代码来处理“未处理”异常,但它仍然强制我使用“退出”函数退出程序,或者默认情况下调用“中止”。是否可以避免这种情况,以便在调用“未处理”后继续正常执行应用程序?

【问题讨论】:

    标签: c++ exception-handling unhandled-exception


    【解决方案1】:

    没有。 set_terminate 允许您提供回调以在程序退出时运行,而不是 而不是 程序退出。

    另外,你抛出了const char*(有点)但试图捕捉int,这就是你的异常没有被处理的原因。只需正确抓住它。

    【讨论】:

    • int 只是为了举例。
    【解决方案2】:

    不可能 - 当Unhandled 被调用时,你的程序已经崩溃并且正在死亡。

    如果你想继续你的程序,只需捕获异常;

    ...
    catch (const char *)
    {
        cout << "Unhandled exception!" << endl;
        // continue......
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-10
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多