The NullPointerException in Java seems to only report that it occurred on a particular line of code. Is it possible to alter that exception to state which variable was null if there is more than one variable used in a line of code?
2 Answers
No, the debug information in the class file does not contain enough information to allow this.
You can, however, improve on the situation. There are two things that can cause a NPE to be thrown:
- A
.dereferencing a variable, likefoo.bar(). - A
[indexing an array, likeargs[0].
If you write your code so there is only one of these on a given code line, there is simply no doubt about which one caused the NPE. It will introduce a lot of temporary variables but then you have more information readily available when debugging.
4 Comments
invokevirtual instruction, which takes only ONE operand. Then you can track back to which object it was invoked on - just take a little bit of workNo. NullPointerException does not always have to be caused by a variable/identifier being null. E.g. throw new NullPointerException() and throw null. Though it is often the case, it is not strictly required.
In most cases, it is fairly obvious what has caused the NPE. If not, then you may have too much going on in one line of code.
Consider this use case:
foo.doWork(bar1, bar2, bar3); Here it is obvious that foo is `null.
Another case:
foo.doWork(bar.get(), bar2.get()) Here it could be foo, bar, or bar2.
The point is, that armed with this information and a breakpoint, it should be obvious what was null. If worse comes to worse, a static code analyzer like FindBugs could also give you some hints.
5 Comments
null and then throws an NPE before doing work. For instance, some collections do this to avoid corrupting the data structure. Other application may be to just avoid the NPE happening organically.Integer val = null and then passing it to someMethod(int i) like so: someMethod(val);
something.getThis().getThat().getAnotherThing().whyAmIStillChaining().seriouslyWtf()all on one line and get an NPE, the only easy way to figure it out is to pull it all apart and recompile/rerun. It's why I wish they had put the Elvis operator in Java 7. Oh well. I had this problem recently too -.-