我有以下示例:
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;
}
我编写了这段处理“未处理”异常的代码,但它仍然强制我使用“退出”函数退出程序,或者它默认调用“中止”。是否可以避免这种情况,以便我在调用“Unhandled”后继续正常执行应用程序?
最佳答案
没有。 set_terminate
允许您提供在程序退出时运行的回调,而不是而不是程序退出。
此外,您抛出了 const char*
(某种程度上)但试图捕获 int
,这就是您的异常未被处理的原因。只需正确捕获它即可。
关于c++ - 未处理的异常 - 强制程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382254/