如何捕获空指针异常? [英] How to catch the null pointer exception?

查看:2634
本文介绍了如何捕获空指针异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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 ++中没有null pointer exception这样的东西。你可以捕获的唯一的例外是,由 $ throw 表达式显式抛出的异常(正如Pavel指出的,一些标准的C ++异常由标准运算符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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆