未处理的异常 - 强制程序退出

时间:2014-08-19 11:28:21

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

我有以下示例:

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

我编写了这个处理'未处理'异常的代码,但它仍然强制我使用'exit'函数退出程序,或默认调用'abort'。可以避免这种情况,以便在调用“未处理”之后继续正常执行应用程序吗?

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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

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

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