Sometimes it happens that I have written a code to check NullPointerException like below,
if(str!=null)
{
doSomething();
}
and the null check itself throws NUllPointerException.
How to solve it.
Edited: Actually this code was getting null pointer,
Map params = new HashMap();
if(params != null && params.get("requestType"))
{
//some null safe code goes here
}
i understood later that params.get() was throwing null pointer exception.
You seem to be saying that:
if (str != null) {
doSomething();
}
is throwing a NullPointerException
in the comparison.
That is impossible. So I expect that what is really happening is one of the following:
You have misinterpreted the stack trace, and the NPE is not being thrown there.
The actual code is substantially different to the illustrative example.
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.
You have managed to seriously confuse your IDE. (Sometimes you can get very strange behaviour from a confused IDE ...)
The only situations where that code might give an NPE that is not an artefact of something else you are doing wrong is if have a damaged Java (or IDE) installation, or if your hardware is faulty. I would discount those explanations as basically implausible.
Update
Now you say that:
Map params = new HashMap();
if(params != null && params.get("requestType"))
{
//some null safe code goes here
}
throws an NPE in params.get
. I have to say that this is nonsense.
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
.
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
.
My previous conclusions stand. This is impossible.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With