I am using Sonar and I have got this kind of violation from it for a peace of my code:
Correctness - Possible null pointer dereference
Has anyone know about this rule in findbugs? I searched a lot but I can not find a good sample code (in Java) which describe this rule, unfortunately findbugs site did not have any sample code or good description about this rule.
Why does this violation appear?
a sample code is something like this.
String s = null ;
if (today is monday){
s = "Monday" ;
else if (today is tuesday){
s = "Tuesday" ;
}
System.out.println(s.length()); //Will throw a null pointer if today is not monday or tuesday.
It says here
NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)
There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.
If you would have posted some code it would be easier to answer.
EDIT I don't see a lot of documentation but here is one example! Hope this helps!
Okay
This is two simple Examples :
First one gives a : Possible null pointer dereference
1. Error
ArrayList a = null;
a.add(j, PointSet.get(j));
// now i'm trying to add to the ArrayList
// because i'm giving it null it gives me the "Possible null pointer dereference"
2. No Error
ArrayList a = new ArrayList<>();
a.add(j, PointSet.get(j));
// adding elements to the ArrayList
// no problem
Simple ?
I got this issue with the following piece of code:-
BufferedReader br = null;
String queryTemplate = null;
try {
br = new BufferedReader(new FileReader(queryFile));
queryTemplate = br.readLine();
} catch (FileNotFoundException e) {
// throw exception
} catch (IOException e) {
// throw exception
} finally {
br.close();
}
Here, the br BufferedReader can be null in br.close(). However it can only be null if new BufferedReader() fails, in which case we are throwing the relevant exceptions.
This is thus a false warning. Findbugs docs mention the same:-
This may lead to a NullPointerException when the code is executed.
Note that because FindBugs currently does not prune infeasible
exception paths, this may be a false warning.
In simple language, if a variable value is assigned as null, and you try to access it with any inbuilt method like add/get. Then null pointer dereference issue comes with SONAR. Because there are changes for it go null, and throw null pointer exception. Try to avoid it if possible.
For example:
File file=null;
file.getName();
will throw "Possible null pointer dereference"
It may not happen directly as mentioned in the example, it can be unintentionally.
Related
How can I catch in exception in Java parameters
Just one example, in code like this
MyClass obj = null;
logger.info("the field is " + obj.field);
a null pointer exception is thrown. Is there a way to automatically do this:
MyClass obj = null;
try {
logger.info("the field is " + obj.field);
} catch(Exception e) {}
Perhaps using Spring AOP, annotations, etc?
Edit: I want something that will catch any exception, so that I never have an exception thrown from a line of code that tries to log.
No there isn't. And you shouldn't do wrap your code in try catch. This may avoid you some runtime exceptions but also could hide real code issues. You could use the Null Object pattern. You create a marker class with empty fields and if a value in your code should be null you assign it to an instance of this marker class. That should work for code under your control, however it doesn't guarantee third party libraries wouldn't throw NPE.
Edit: I want something that will catch any exception, so that I never have an exception thrown from a line of code that tries to log.
That can never be achieved. What you are asking for essentially is a try catch block at the start to end of the main method. Even though you still can get exceptions from other threads for example
I'm currently having issues with null analysis on both Eclipse and IntelliJ where they don't understand a piece of code that handles null pointer exceptions. Basically I got the method below:
#Nullable
public static <T> T getValueOrNull(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result).orElse(null);
} catch (NullPointerException e) {
return null;
}
}
Normally I wouldn't catch those types of exceptions but in the project I'm working this method makes things much more readable.
It is called this way:
getValueOrNull(() -> obj.getObj2().getObj3()...getObjN())
This call returns the value or null if anything is null in the chain.
The problem is that null analysis will complain about possible null pointer exceptions while calling the method. While it is true that any of them may be null the method is handling that error. Is there a way to either skip null analysis for the parameters of a method or help the analyzer understand what is happening?
It seems that even a very simple test where null pointer exceptions are being caught still flags potential null issues inside the try block. That makes me think that try catch blocks are never even considered by the analyzer.
Also I do know that there are other ways of doing this such as the code below but if possible I'd like to be able to use what we are currently doing due to readability. Also even the code below has issues with the null analysis for the IDEs mentioned above.
Optional.ofNullable(objectA)
.map(a -> a.getObjectB())
.map(b -> b.getObjectC())
.map(c -> c.getObjectD())
.map(d -> d.getObjectE())
.map(e -> e.getName())
.orElse("");
While doing bug analysis using klocwork, I am getting warning Null pointer dereference of 'nextLineDn' where null is returned from a method.
Apparently other static analysis tool findbug also gives same warning.
But clearly i am checking for null/empty before using it.
int noOfLines = device.getLines().size();
if( lineNo != 0 && noOfLines > lineNo ) // if next line exists
{
nextLineDn = device.getDn(lineNo+1);
if(!Util.isNullOrEmpty(nextLineDn))
{
return (nextLineDn.contains("#")) ? nextLineDn.split("#")[0] : nextLineDn;
}
}
class Util :
public static boolean isNullOrEmpty(String str) {
return (str == null || str.isEmpty());
}
can someone give me some idea on this?
i am getting so many warning with same conditions.Dont know what else can be done to remove the warning.
Since Klocwork Insight is a static source code analysis tool, it might not be able to further decipher that you have a method named isNullOrEmpty() in Util class, wherein you are actually doing a null check. So, it is showing warnings in your IDE.
Static analysis tool tries to find potential flaws in advance. So, here Klocwork would tell : device.getDn() might return null, be careful with using nextLineDn.
But, if you put code like (nextLineDn!=null), I guess it would not flag a warning there. (Try and let us know)
My java code throws exception e which is null (debug shows e==null)
How can the code catch this at:
} catch (IOException e) {
e.printStackTrace();
}
If e is null how can it have a type?
Two ideas occur to me:
1) What most debuggers display is e.toString(). If you have an exception object whose toString() is returning null (or "null"), that might explain what you're seeing. What type does the debugger say e is?
2) Another possibility is that your source code doesn't match the class currently executing, and you're at a different line than you think you are. I've been caught out that way.
I am trying to execute java program but it seems the current code is returning null pointer exception on this piece of code:
IntegerDesc yearOfBuildDesc =
(IntegerDesc) myConcept.getAllAttributeDescs().get("yearOfBuild");
try {
query.addAttribute(yearOfBuildDesc,
yearOfBuildDesc.getAttribute("yearOfBuild"));
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Do you know where the problem might come from?
Probably one of the following:
myConcept is null, so .getAllAttributeDescs() falls over.
myConcept.getAllAttributeDescs() returns null, so .get("yearOfBuild") falls over.
myConcept.getAllAttributeDescs().get("yearOfBuild") returns null, leading yearOfBuildDesc to be null when you call getAttribute on it, which causes an exception.
query is null, causing .addAttribute(...) to fall over.
Something inside the getAllAttributeDescs method causes a null pointer exception when invoked.
Something inside the get method causes a null pointer exception when invoked.
Something inside the addAttribute method causes a null pointer exception when invoked.
Something inside the getAttribute method causes a null pointer exception when invoked.
Your initial code throws a ParseException, the call to whose printStackTrace method then throws a null pointer exception (unlikely).
In general, when hunting down null pointer exceptions, you should look for problems with:
Select expressions (i.e. x.y) - can the x be null?
Method calls - can the method throw a null pointer exception?
I've excluded the possibility that e is null here, since it's the exception you just caught.
yearOfBuildDesc.getAttribute("yearOfBuild");
Above line will throw NullPointerException if yearOfBuildDesc is null, add a null check.
yearOfBuildDesc might be null. Test before using it in the try catch
myConcept might also be null, check also.