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.
这篇关于如何捕捉空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
当没有异常时,C++ 异常会以何种方式减慢代码速In what ways do C++ exceptions slow down code when there are no exceptions thown?(当没有异常时,C++ 异常会以何种方式减慢代码速度?)
为什么要捕获异常作为对 const 的引用?Why catch an exception as reference-to-const?(为什么要捕获异常作为对 const 的引用?)
我应该何时以及如何使用异常处理?When and how should I use exception handling?(我应该何时以及如何使用异常处理?)
C++中异常对象的范围Scope of exception object in C++(C++中异常对象的范围)
从构造函数的初始化列表中捕获异常Catching exceptions from a constructor#39;s initializer list(从构造函数的初始化列表中捕获异常)
C++03 throw() 说明符 C++11 noexcept 之间的区别Difference between C++03 throw() specifier C++11 noexcept(C++03 throw() 说明符 C++11 noexcept 之间的区别)