2

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.

Jad Chahine
  • 6,849
  • 8
  • 37
  • 59
deepak
  • 133
  • 1
  • 4
  • 13
  • 2
    Don't set it to `null` in the first place. Why not use the empty String, `""`? – JonK Apr 01 '15 at 08:22
  • I agree with @JonK, moreover if you're not the one setting it to null you could always just check the value `if (name != null)`. – ArnonZ Apr 01 '15 at 08:24

2 Answers2

4

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.

Community
  • 1
  • 1
Juxhin
  • 5,068
  • 8
  • 29
  • 55
4

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) {....}
npinti
  • 51,780
  • 5
  • 72
  • 96
  • 2
    He could use Java 1.8's `Optional` to always avoid it – Loki Apr 01 '15 at 08:26
  • 1
    @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. – npinti Apr 01 '15 at 08:30