How to catch the null pointer exception?(如何捕捉空指针异常?)
问题描述
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.
这篇关于如何捕捉空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何捕捉空指针异常?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01