在NullPointerException
Java 中似乎只报告它发生在特定的代码行上。如果一行代码中使用了多个变量,是否可以更改该异常以声明哪个变量为空?
2 回答
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.
不。 NullPointerException 并不总是由变量/标识符引起null
。例如throw new NullPointerException()
和throw null
。虽然经常出现这种情况,但并不是严格要求的。
在大多数情况下,导致 NPE 的原因是相当明显的。如果没有,那么您可能在一行代码中发生了太多事情。
考虑这个用例:
foo.doWork(bar1, bar2, bar3);
这里很明显foo
是`null。
另一个案例:
foo.doWork(bar.get(), bar2.get())
这里可能是foo
, bar
, 或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.