调试 nullPointerException 的好方法 [英] A good way to debug nullPointerException

查看:36
本文介绍了调试 nullPointerException 的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Eclipse 并在 Java 中编程.有时我会遇到一个 nullPointerException,它会困扰我好几个小时.无论如何,有没有更好地调试 nullPointerExceptions 并找出哪些变量值以及其他会导致 null Pointer Exceptions 的事情.

I am using eclipse and programing in java. Sometimes I come across a nullPointerException that will plague me for hours. Is there anyway to debug nullPointerExceptions better and figure out what variable values are and other things that would cause null Pointer Exceptions.

推荐答案

查看堆栈跟踪并读取抛出 NullPointerException 的行号.几乎总是,该行有一些方法调用,如

Look at the stack trace and read the line number where the NullPointerException is thrown. Almost always, the line has some method invocation like

x.getValue()

如果 xnull,你会得到一个 NullPointerException.如果堆栈跟踪顶部的方法不是您的代码,请一直跟踪堆栈,直到找到您的代码.在这种情况下,您经常将 null 传递给不喜欢 null 参数的方法.找到它并修复它.

If x is null, you get a NullPointerException. If the method at the top of the stack trace is not your code, trace the stack all the way back until you do reach your code. Very often in this case, you are passing null to a method that doesn't like null parameters. Find it and fix it.

此外,当您遇到不属于您的方法抛出 NullPointerException 时,请阅读文档.例如,查看 String.replace(CharSequence target, CharSequence replacement):

Also, very often when you encounter a method that is not yours that is throwing a NullPointerException, read the documentation. For example, look at String.replace(CharSequence target, CharSequence replacement):

投掷:

NullPointerException - 如果 targetreplacementnull.

NullPointerException - if target or replacement is null.

没有比这更清楚的了!

这是一个例子:

查看第 4 行,我们看到 foo.bar().这意味着 foonull.那个很容易.我们再看一个例子:

Looking at line 4, we see foo.bar(). This implies that foo is null. That one is easy. Let's look at another example:

回溯到您的代码,我们看到 s.replace(target, replacement) 正在抛出.我们应该检查targetreplacement.让我们附加一个调试器:

Tracing back to your code, we see that s.replace(target, replacement) is throwing. We should inspect target and replacement. Let's attach a debugger:

啊哈!替换null.您可以在 Eclipse 中做同样的事情.在抛出异常时设置断点,并使用它来检查方法的参数.我在这里很原始,因为我来自一个思想流派,我真诚地相信,如果每个人先学会以艰难的方式去做这件事,他们都会过得更好.泄漏的抽象等等.

Aha! replacement is null. You can do the same thing in Eclipse. Set a breakpoint for when an exception is thrown, and use it to inspect the parameters to your method. I'm primitive here because I come from a school of thought where I genuinely believe everyone would be better off if they learned to do it the hard way first. Leaky abstractions and all that.

这篇关于调试 nullPointerException 的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆