Eliminating Null Pointer Exceptions
How to avoid null pointer exception in java - Stack Overflow
Java - ignore exception and continue - Stack Overflow
How to avoid NullpointerException without null check in java - Stack Overflow
So, this is more of a thought experiment and something I've been wondering for a while. IMO, the existence of null pointers in a memory safe language is contrary to its purpose. What if all uninitialized objects had a default value of empty instead of null? There would be no memory allocation until it was explicitly defined. All interactions with the uninitialized object would behave as if the object were empty and did not fire Null Pointer Exceptions.
Attack!
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 null from your methods, unless it is really necessary, for instance:
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.
If on the other hand, you return null, you would need to do something like so:
List<String> userNames = this.getUsernames();
if(userNames != null)
for(String userName : userNames) {....}
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 null into your String.
A general rule that has been taught to me by fellow SO users is to always catch NPEs as early as possible (to avoid collateral damage throughout your application).
For parameter validation you'll most probably need to use Objects#requireNonNull.
You may also declare a simple if-statement depending on the scenario, like so - if (name != null)
You also must realise that in some cases null may 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?
Upon further investigation, it seems that Java 1.8 also offers a new Optional class ( java.util.Optional ) which seems very useful and cleaner. Take a look at this Oracle document.
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.
You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (NullPointerException npe) {
// Lulz @ your NPE
Logger.log("No user info for " +username+ ", will find some way to cope");
}
You can avoid many null checks by using Yoda Expressions, for example
if ("Hello".equals(str))
"Hello", as a literal, is never null and the built-in equals method will check str for null-ness. The alternative str.equals("Hello") would require you to check str first.
Some folk find them obfuscating, and it's not always possible to arrange your syntax accordingly.
I guess theres something like a homework to do? Eventually the teacher wants you to use a Try Catch Block?
try{
//what you want to do when its not null
}
catch (NullPointerException exp){
//what happens if its null
}
It try's to perform the code in the Try block, but if a NullPointerException occurs, you can handle it in the Catch block. Maybe, just maybe thats what you want.