尝试/捕获C++程序中的所有块不起作用
C++ 中的 Try/catch 块未被“捕获”。我正在尝试使用一个 catch 块来获取所有异常。
#include <iostream>
#include <exception>
using namespace std;
int main()
{
try
{
throw 1;
}
catch (exception& e)
{
cout << "ERROR: " << e.what() << endl;
return 1;
}
return 0;
}
回答
throw 1;会抛出一个int. 由于您没有捕获int,异常未被捕获,这是未定义的行为。虽然可以抛出任何东西,但总是更喜欢抛出一个派生自std::exception. 你可以int用catch(int e)或来捕捉catch(...),但真的没有理由这样做。
如果您使用catch(...),那么您不知道对象的类型,因此无法访问任何成员、属性或其他方面,因此您无法*收集有关抛出内容的任何信息。这不应该被使用。
*有有途径获得有关抛出的对象的信息,但它要容易得多正好赶上摆在首位的权利类型
- *"the exception goes uncaught, which is undefined behavior"* - No, it's pretty well defined as calling `std::terminate`.