2

I would like to ask can sonar find null pointer exception caused by java virtual machine at run time?? if yes please tell me which sonar rule do it for us. I am very much puzzled with it as there are some rules exist in sonar findbugs profile which say sonar catch null pointer exception. One of findbugs rule Avoid Throwing Null Pointer Exception say we should avoid throwing null pointer exception.

please clarify me on that can sonar catch null pointer exception or not threw by JVM?? OR it can catch only customized null pointer exception(generated by developer) and what these sonar rules meant for(null pointer exception, null pointer dereference etc.) What are the rules to use Sonar?

Braiam
  • 1
  • 11
  • 47
  • 78
shekhar verma
  • 489
  • 2
  • 9
  • 22

1 Answers1

1

Yes, Sonar can detect NullPointerExceptions (NPEs) thrown by the JVM by using the FindBugs tool under the hood. However, it can not do so dynamically at runtime, because FindBugs is a static analysis tool.

From the FindBugs detectors, choose those with the NP_ prefix in their key, such as NP_ALWAYS_NULL. There are roughly 30 such detectors that deal with null pointer analysis.

Note that FindBugs works by static analysis of the code. In other words, it does not dynamically "catch" NPEs or somehow perform a simulated run of the code and "catch" NPEs. This would be hard to do because test cases would be required for every possible code path. Instead, FindBugs only analyses the class files using its detectors.
So you are not going to find all cases where NPEs can occur, but due to the sheer number of detectors, you are going to catch most. Also, some FindBugs detectors in this field are quite sophisticated, even though there is always room for improvement.

Note also that in order to help the detectors do their jobs, you may have to annotate method arguments and return values with null pointer analysis annotations (also in JSR305 here). If you search SO for these annotations, you will find lots of helpful advice on their correct usage in various environments.

barfuin
  • 16,865
  • 10
  • 85
  • 132