如何捕捉空指针异常?

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 newdynamic_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.

这篇关于如何捕捉空指针异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)