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?
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.
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