开发者

How to handle NullPointerException in Java [closed]

开发者 https://www.devze.com 2023-01-01 04:53 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably 开发者_StackOverflowanswered in its current
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably 开发者_StackOverflowanswered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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


You should avoid 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.

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

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


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


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

Generally, try to do more research in advance.

0

精彩评论

暂无评论...
验证码 换一张
取 消