问题描述
try {
int* p = 0;
*p = 1;
} catch (...) {
cout << "null pointer." << endl;
}
我试图捕捉这样的异常,但它不起作用,有什么帮助吗?
I tried to catch the exception like this but it doesn't work,any help?
推荐答案
C++ 中没有空指针异常"这样的东西.您可以捕获的唯一异常是 throw
表达式显式抛出的异常(另外,正如 Pavel 所指出的,一些标准 C++ 异常由标准 operator new
、dynamic_cast
等).C++ 中没有其他例外.取消引用空指针、除以零等不会在 C++ 中产生异常,它会产生未定义行为.如果您希望在这种情况下抛出异常,您有责任手动检测这些条件并明确地执行 throw
.这就是它在 C++ 中的工作方式.
There's no such thing as "null pointer exception" in C++. The only exceptions you can catch, is the exceptions explicitly thrown by throw
expressions (plus, as Pavel noted, some standard C++ exceptions thrown intrinsically by standard operator new
, dynamic_cast
etc). There are no other exceptions in C++. Dereferencing null pointers, division by zero etc. does not generate exceptions in C++, it produces undefined behavior. If you want exceptions thrown in cases like that it is your own responsibility to manually detect these conditions and do throw
explicitly. That's how it works in C++.
您似乎正在寻找的其他任何东西都与 C++ 语言无关,而是特定实现的功能.例如,在 Visual C++ 中,系统/硬件异常可以转换"为 C++ 异常,但这种非标准功能是有代价的,通常不值得付出代价.
Whatever else you seem to be looking for has noting to do with C++ language, but rather a feature of particular implementation. In Visual C++, for example, system/hardware exceptions can be "converted" into C++ exceptions, but there's a price attached to this non-standard functionality, which is not normally worth paying.
这篇关于如何捕捉空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!