可以将Java的NullPointerException更改为报告哪个变量为null吗? [英] Can Java's NullPointerException be changed to report on which variable was null?
问题描述
Java中的 NullPointerException
似乎仅报告它发生在特定的代码行上.如果在一行代码中使用多个变量,是否可以更改该异常以声明哪个变量为null?
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?
推荐答案
否,类文件中的调试信息包含的信息不足以允许此操作.
No, the debug information in the class file does not contain enough information to allow this.
但是,您可以改善这种情况.可以导致抛出NPE的原因有两点:
You can, however, improve on the situation. There are two things that can cause a NPE to be thrown:
- 取消引用变量的
.
,例如foo.bar()
. - 一个
[
为数组建立索引,例如args [0]
.
- A
.
dereferencing a variable, likefoo.bar()
. - A
[
indexing an array, likeargs[0]
.
如果您编写代码,那么在给定的代码行中只有其中的 个,则毫无疑问,是哪个代码导致了NPE.它将引入一个 lot 临时变量,但是在调试时,您将获得更多可用信息.
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.
这篇关于可以将Java的NullPointerException更改为报告哪个变量为null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!