How to avoid null pointer exception in java

17,317

Solution 1

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) {....}

Solution 2

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.

Share:
17,317
deepak
Author by

deepak

Updated on June 04, 2022

Comments

  • deepak
    deepak almost 2 years

    I am curious to know proper way to avoid NullPointerExceptions.

    try
    {
        String name = null;
        System.out.println("name=" + name.toString());
    }
    catch(Exception e)
    {
        System.out.println("Exception Occured" + e.getMessage());
    }
    

    Here I am just catching and showing the exception message. I want to know proper way to handle this or avoiding such situations.

  • Loki
    Loki about 9 years
    He could use Java 1.8's Optional to always avoid it
  • npinti
    npinti about 9 years
    @Loki: I do not know what version the OP is using, so I tried to go with the most generic one, but other than that, yes I guess the OP could use the Optional approach.