如何在Java中处理NullPointerException

roz*_*zer 5 java

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

Dan*_*ann 23

你应该避免使用NullPointerExceptions:

if(someObject != null) {
    someObject.doSomething();
} else {
    // do something other
}
Run Code Online (Sandbox Code Playgroud)

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.

try {
    someObject.doSomething();
} catch(NullPointerException e) {
    // do something other
}
Run Code Online (Sandbox Code Playgroud)

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


Fin*_*arr 14

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

  • 虽然你真的应该考虑`//愚蠢的东西'以使它不那么愚蠢 (22认同)
  • 也许是因为不是每个人都根据答案的科学合理性和完整性进行投票.相反,他们根据他们认为有趣和/或可能涉及的答案进行投票. (3认同)
  • @Finbarr这是不可能以违反规则的方式投票(据我所知),但绝对可能投票不正确.如果您认为所有答案都是错误的,并且您认为所有答案都是正确的,那么您的投票结果不正确,但您不会因此而被暂停.你应该赞成你认为有用的答案 (2认同)