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

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

问题描述

我在java中使用eclipse和编程。有时我遇到一个nullPointerException会让我困扰好几个小时。有没有更好地调试nullPointerExceptions,并找出什么变量值和其他会导致空指针异常的东西。

解决方案

在堆栈跟踪中,读取抛出 NullPointerException 的行号。几乎总是,该行有一些方法调用,如

  x.getValue()

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



另外,当您遇到不是您的方法时,经常会抛出 NullPointerException ,阅读文档。例如,查看 String.replace(CharSequence target,CharSequence replacement)



< blockquote>

抛出



NullPointerException - 如果目标替换 null


它不会比这更清楚!



这里有一个例子:





看第4行,我们看到 foo.bar()。这意味着 foo null 。那个很容易我们来看另一个例子:





跟踪代码,我们看到 s.replace(target,replacement)正在抛出。我们应该检查目标替换。让我们附上一个调试器:





呵呵! 替换 null 。你可以在Eclipse中做同样的事情。为抛出异常时设置一个断点,并使用它来检查您的方法的参数。我原来在这里,因为我来自一个思想学派,我真的相信每个人都会更好,如果他们学会了这样做的艰难的方式。泄漏抽象和所有这些。


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.

解决方案

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()

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.

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):

Throws:

NullPointerException - if target or replacement is null.

It doesn't get much clearer than that!

Here's an example:

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

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:

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天全站免登陆