找出什么变量在程序上抛出NullPointerException [英] Find out what variable is throwing a NullPointerException programatically

查看:96
本文介绍了找出什么变量在程序上抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用这些技术找出Java中的变量是否为空:




  • if var == null) - >太多工作

  • try {...} catch(NullPointerException e){...} - >它告诉我使用调试器 - >手动执行异常




考虑这一行代码:

  if(this.superSL.items。 get(name).getSource()。compareTo(VIsualShoppingList.Source_EXTRA)== 0){

想知道是否有一种通用的方式来在程序中找出在特定的代码区域中抛出NullPointerException的变量(不只是行)。在示例中,知道

解决方案

由于可能导致空指针异常,甚至不涉及变量:

  throw new NullPointerException(); 

我不得不说,没有通用的方法来将空指针异常定向到特定的



您最好的选择是在每行上放置尽可能少的语句,以便明显导致空指针异常。请考虑在问题中重构代码,看起来像这样:

 列表项= this.superSL.items; 
String name = items.get(name);
String source = name.getSource();
if(source.compareTo(VIsualShoppingList.Source_EXTRA)== 0){
// ...
}

有更多的代码行可以肯定。但它也更可读,更易于维护。


I know I can find out if a variable is null in Java using these techniques:

  • 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

Consider this line of code:

if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0)  {

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屋!

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