3

NullPointerExceptionJava 中似乎只报告它发生在特定的代码行上。如果一行代码中使用了多个变量,是否可以更改该异常以声明哪个变量为空?

4

2 回答 2

4

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, like foo.bar().
  • A [ indexing an array, like args[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.

于 2012-09-25T22:23:27.847 回答
1

不。 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.

于 2012-09-25T22:16:57.740 回答