找出以编程方式抛出NullPointerException的变量 [英] Find out what variable is throwing a NullPointerException programmatically
问题描述
我知道我可以使用这些技术找出Java中的变量是否为空:
I know I can find out if a variable is null in Java using these techniques:
- if
( var == null)
- >工作太多 -
try {...} catch(NullPointerException e){...}
- >它告诉我什么行抛出异常 - 使用调试器 - >手动,太慢
- if
(var==null)
-> too much work try { ... } catch (NullPointerException e) { ...}
-> it tells me what line is throwing the exception- using the debugger -> by hand, too slow
考虑以下代码行:
if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0) {
I想知道是否有通用的方法以编程方式找出哪个变量(不仅仅是行)在某个代码区域中抛出NullPointerException。在示例中,知道
I would like to know if there's a generic way to find out programatically what variable (not just the line) is throwing the NullPointerException in a certain area of code. In the example, knowing that
推荐答案
因为即使没有涉及变量也可能导致空指针异常:
Since it's possible to cause a null pointer exception without even involving a variable:
throw new NullPointerException();
我不得不说没有通用的方法可以将空指针异常固定到特定的变量。
I would have to say that there is no generic way to pin down a null pointer exception to a specific variable.
最好的办法是尽可能少地在每一行上添加语句,以便明白导致空指针异常的原因。考虑在问题中重构代码,看起来像这样:
Your best bet would be to put as few as possible statements on each line so that it becomes obvious what caused the null pointer exception. Consider refactoring your code in the question to look something like this:
List items = this.superSL.items;
String name = items.get(name);
String source = name.getSource();
if (source.compareTo(VIsualShoppingList.Source_EXTRA) == 0) {
// ...
}
确保更多的代码行。但它也更具可读性和可维护性。
It's more lines of code to be sure. But it's also more readable and more maintainable.
这篇关于找出以编程方式抛出NullPointerException的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!