在异常情况下,我希望我的程序停止处理,向std::cerr
输出错误,清理并退出。
但是,调用 exit()
不会调用任何已构造对象的所有析构函数。我希望很好地调用析构函数,所以我将所有代码包装在 try-catch
block 中,如下所示:
int main(int argc, char** argv){
try {
bool something_is_not_right = false;
/* lots of variables declared here */
/* some code that might set something_is_not_right to true goes here */
if(something_is_not_right){
std::cerr << "something is not right!!!" << std::endl;
throw '\0'; // dummy unused variable for throwing.
}
}
catch (...) {}
return 0;
}
通过这种方式,我可以保证销毁所有变量。但我似乎找不到让 C++ 什么都不throw
的方法。 throw;
在C++中有特殊含义;它没有抛出任何东西。
有没有办法抛出
什么都没有?
最佳答案
没有
不可能什么都不扔。你需要扔东西。虽然您可能已经看到人们在不使用任何东西的情况下使用 throw
关键字,但这仅意味着他们正在重新抛出当前处理的异常。
关于c++ - 在 C++ 中有可能什么都不抛出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43675700/