如何在 Java 中处理 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2931065/
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-08-13 14:36:22  来源:igfitidea点击:

How to handle NullPointerException in Java

java

提问by rozer

How to handle NullPointerExceptionin Java? Please provide details so I can get rid of this problem

NullPointerException在Java中如何处理?请提供详细信息,以便我摆脱这个问题

回答by Finbarr

try {
    // something stupid
} catch(NullPointerException e) {
    // probably don't bother doing clean up
} finally {
    // carry on as if nothing went wrong
}

回答by Max Leske

You should really make yourself familiar with the concept of a variable being null. Checkout the API: http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html

您真的应该让自己熟悉变量为空的概念。签出API:http: //java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html

Generally, try to do more research in advance.

一般来说,尽量提前做更多的研究。

回答by Daniel Engmann

You should avoid NullPointerExceptions:

您应该避免 NullPointerExceptions:

if(someObject != null) {
    someObject.doSomething();
} else {
    // do something other
}

Normally you should ensure that the objects which you use are not null.

通常你应该确保你使用的对象不为空。

You also can catch the NullPointerException and except using an if-condition.

您还可以捕获 NullPointerException 并且使用 if 条件除外。

try {
    someObject.doSomething();
} catch(NullPointerException e) {
    // do something other
}

Normally there is a bug in your code, when a NullPointerException occurs.

通常,当 NullPointerException 发生时,您的代码中存在错误。