java java中如何避免空指针异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29385992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:10:25  来源:igfitidea点击:

How to avoid null pointer exception in java

javaexception-handlingnullpointerexception

提问by deepak

I am curious to know proper way to avoid NullPointerExceptions.

我很想知道避免NullPointerExceptions 的正确方法。

try
{
    String name = null;
    System.out.println("name=" + name.toString());
}
catch(Exception e)
{
    System.out.println("Exception Occured" + e.getMessage());
}

Here I am just catching and showing the exception message. I want to know proper way to handle this or avoiding such situations.

在这里,我只是捕获并显示异常消息。我想知道处理这种情况或避免这种情况的正确方法。

回答by Juxhin

Could you elaborate on what you mean be avoiding NPEs? It can be done in many ways. In your case you shouldn't be passing nullinto your String.

您能否详细说明避免 NPE 的意思?它可以通过多种方式完成。在你的情况下,你不应该传入null你的字符串。

A general rule that has been taught to me by fellow SO users is to alwayscatch NPEs as early as possible (to avoid collateral damage throughout your application).

其他 SO 用户教给我的一般规则是始终尽早捕获 NPE(以避免在整个应用程序中造成附带损害)。

For parameter validation you'll most probably need to use Objects#requireNonNull.

对于参数验证,您很可能需要使用Objects#requireNonNull

You may also declare a simple if-statement depending on the scenario, like so - if (name != null)

您还可以根据场景声明一个简单的 if 语句,如下所示 - if (name != null)



You also must realise that in some cases nullmay be required and thus handling such an NPE would be different. If you are not going to actually do something with the Exception, it should not be caught as it's possibly harmful to catch an exception and then simply discard it. The following discusses when you ought to throw an exception or not - When to throw an exception?

您还必须意识到在某些情况下null可能需要,因此处理此类 NPE 会有所不同。如果您不打算对 实际执行某些操作Exception,则不应捕获它,因为捕获异常然后简单地将其丢弃可能有害。下面讨论何时应该抛出异常 -何时抛出异常?



Upon further investigation, it seems that Java 1.8 also offers a new Optionalclass ( java.util.Optional ) which seems very useful and cleaner. Take a look at this Oracle document.

经过进一步调查,Java 1.8 似乎还提供了一个新Optional类( java.util.Optional ),它看起来非常有用和清晰。看看这个Oracle 文档

回答by npinti

Other than catching the error, if you are going to work with something which might be null, you might want to throw in null checks.

除了捕获错误之外,如果您要处理可能为空的内容,您可能需要进行空检查。

What you could do to reduce the chances of having to make null checks, would be to never return nullfrom your methods, unless it is really necessary, for instance:

为了减少必须进行空检查的机会,您可以做的是永远不要null从您的方法中返回,除非确实有必要,例如:

public IList<String> getUserNames()
{
     //No usernames found...
     return new ArrayList<String>();

     //As opposed to returning null
     return null;
}

By returning the empty list, a call to the above code would result into something like so: for(String name : this.getUserNames()) {...}. If no user names where found, the loop will not execute.

通过返回的空单,上面的代码的调用会导致到的东西,像这样: for(String name : this.getUserNames()) {...}。如果没有找到用户名,循环将不会执行。

If on the other hand, you return null, you would need to do something like so:

另一方面,如果您返回 null,则需要执行以下操作:

List<String> userNames = this.getUsernames();
if(userNames != null)
     for(String userName : userNames) {....}