空检查抛出NullPointerException [英] Null Check throws NullPointerException

查看:128
本文介绍了空检查抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候我碰巧写了一个代码来检查NullPointerException,如下所示,

Sometimes it happens that I have written a code to check NullPointerException like below,

if(str!=null)
{
    doSomething();
} 

并且空检查本身会引发NUllPointerException。

and the null check itself throws NUllPointerException.

如何解决。

编辑:
实际上,此代码获取的是空指针,

Edited: Actually this code was getting null pointer,

Map params = new HashMap();
if(params != null && params.get("requestType"))
{
    //some null safe code goes here
}

后来我了解到params.get()抛出了空指针异常。

i understood later that params.get() was throwing null pointer exception.

推荐答案

您似乎在说:

if (str != null) {
    doSomething();
}

抛出 NullPointerException

is throwing a NullPointerException in the comparison.

这是不可能。因此,我希望真正发生的是以下情况之一:

That is impossible. So I expect that what is really happening is one of the following:


  • 您误解了堆栈跟踪,而NPE是

  • You have misinterpreted the stack trace, and the NPE is not being thrown there.

实际代码与示例有所不同。

The actual code is substantially different to the illustrative example.

您没有执行您认为正在执行的代码。例如,您可能没有重新编译它……或者您正在执行 .class .jar 文件。

You are not executing the code that you think you are executing. For example, you might not have recompiled it ... or you may be executing a stale copy of the .class or .jar file.

您已经设法严重混淆了IDE。 (有时您会从混乱的IDE中获得非常奇怪的行为...)

You have managed to seriously confuse your IDE. (Sometimes you can get very strange behaviour from a confused IDE ...)

该代码可能给出的NPE可能不是您所做的其他事情的假象的唯一情况是,如果Java(或IDE)安装损坏,或者您的硬件出现故障。我会把这些解释视作根本难以置信。

更新

现在您说:

Map params = new HashMap();
if(params != null && params.get("requestType"))
{
    //some null safe code goes here
}

params.get 中抛出NPE。我不得不说这是胡说八道。

throws an NPE in params.get. I have to say that this is nonsense.


  1. 代码无法编译。 params.get 调用不会返回 boolean 或可以自动转换为 boolean

  1. The code won't compile. The params.get call doesn't return something that is boolean or that can be automatically converted to a boolean.

如果我们忽略编译错误,则 params.get 参数 null ,则在线程受限映射上的c $ c>只能抛出NPE。这张地图 是线程受限的,并且先前的检查确保 params 不会 null

If we ignore the compilation errors, then params.get on a thread-confined map can only throw an NPE if params is null. This map is thread-confined, and the previous check ensures that params isn't null.

我以前的结论成立。

提示:这可能是线程问题。如果您使用一个线程更新 HashMap 并与另一个线程一起读取,并且未正确同步,则可能会得到间歇性NPE。

Hint: this could be a threading problem. It is possible to get intermittent NPE's if you update a HashMap with one thread and read it with another, and you don't synchronize properly.

这篇关于空检查抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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