Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar: Possible nullpointer?

I don't know why Sonar thinks that in the following line a NullPointer Exception may occur:

if (file == null || file.listFiles() == null || file.listFiles().length == 0) {//etc}

Do you guys have any idea?

like image 668
Gabriel Avatar asked Sep 15 '15 19:09

Gabriel


1 Answers

Expanding on my comment:

Just because one invocation of file.listFiles() returns non-null does not mean the next one necessarily will do. You cannot in general rely on two invocations of the same method (on the same object, with the same arguments) to return the same value, and any method returning a value of reference type may, in principle, return null. On reflection you will recognize that you often depend getting different results for different invocations of the same method. file.listFiles().length is therefore always an NPE risk.

Even if you expect Sonar to have specific knowledge of the File class (which does not necessarily seem reasonable), it is genuinely possible for evaluation of your compound conditional expression to throw an NPE. All that needs to happen is for the referenced file to be removed between evaluation of file.listFiles() and evaluation of file.listFiles().length.

You could correct this particular issue like this:

File[] files;
if (file == null || (files = file.listFiles()) == null || files.length == 0) { /* ... */ }

Of course, as @zapi said, if file is modifiable and accessible to other threads, then pretty much all bets are off.

like image 139
John Bollinger Avatar answered Sep 26 '22 23:09

John Bollinger