Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle NullPointerException in Java [closed]

Tags:

java

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

like image 575
rozer Avatar asked May 28 '10 17:05

rozer


People also ask

How do I avoid NullPointerException?

Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.

Can NullPointerException be caught?

Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem. The program explicitly throws a NullPointerException to signal an error condition.


1 Answers

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.

like image 62
Daniel Engmann Avatar answered Nov 05 '22 12:11

Daniel Engmann