-1

I have code that is throwing a null pointer exception.

Here is my code:

StringBuilder strName = new StringBuilder(100); 
strName.append(someClassObject.getFirstName().getContent().get(0));
strName.append(" ");
strName.append(someClassObject.getLastName().getContent().get(0));
name = strName.toString();

It is throwing a null pointer exception when trying to retrieve the last name at someClassObject.getLastName().getContent().get(0).


My question is, how to proceed with best practice in catching the null pointer.

What I was thinking something similar to this:

String lastName = (String) someClassObject.getLastName().getContent().get(0);
if(lastName == null) {
    lastName = "";
    LOGGER.warn("Last name is null");
}
strName.append(lastName);

Which I am hesitant since I have to convert the lastName object to a String and then create logic to check if it is null or not.

Or

try { 
    strName.append(someClassObject.getLastName().getContent().get(0));
} catch(NullPointerException e) {
    LOGGER.warn("Last name of the conusmer is null");
}
robben
  • 181
  • 3
  • 13
  • You don't have to convert it to a string to check if it is null – Alex Feb 24 '17 at 18:44
  • 1
    Possible duplicate of [Java if vs. try/catch overhead](http://stackoverflow.com/questions/8621762/java-if-vs-try-catch-overhead) – xandermonkey Feb 24 '17 at 18:45
  • The major problem with your second approach is that you won't be able to tell what was null. It could be `someClassObject`, the return value of `getLastName()`, the return value of `getContent()` or the actual string. – Jim Garrison Feb 24 '17 at 18:46
  • @JimGarrison What if I don't mind which is the one returning null? Just that that whole object is null. I am saying this because that `someClassObject` is very old code that I don't want to touch. – robben Feb 24 '17 at 18:50
  • Those two questions are NOT duplicate!! – robben Feb 24 '17 at 18:51
  • possible dup:http://stackoverflow.com/questions/2033088/java-how-to-check-if-object-is-null – z atef Feb 24 '17 at 18:52
  • 1
    While it's not an answer to your question, you definitely should read this: https://en.wikipedia.org/wiki/Law_of_Demeter (especially pay attention to "In particular, an object should avoid invoking methods of a member object returned by another method.") – avysk Feb 24 '17 at 19:03

3 Answers3

0

The exception only occurs when you call a method withing an already null object (you can debug to see which object is the root null).

In case your null is the someClassObject.getLastName() You could check nullity in java with this oneliner:

String lastName = (someClassObject.getLastName() == null) ? "" : someClassObject.getLastName().getContent().get(0);
Swadish
  • 100
  • 10
0

All the overloads of StringBuilder.append() are null safe. They append the text null if the input is null. Hence, you must be getting the NPE from any one of the methods in the expression someClassObject.getLastName().getContent().get(0).

If these methods are not null safe, then it is better to check for null before chaining the next method than catching NPE. This way you might have to write some boilerplate code, but execution time will be cheaper. Exceptions are costly, even if they are handled.

The other option is, if possible change the methods getLastName(), getContent(), and get(), to make them null safe - return empty value instead of throwing NPE. In this case you have to think how the other users of these methods will react if you make this change.

mitratul
  • 1
  • 1
0

You can use Java 8 Optional to check if object is not null at each level of someClassObject , as follows:

StringBuilder strName = new StringBuilder(100); 
Optional<List<String>> option = Optional.of(someClassObject)
                    .map(SomeClassObject::getLastName).map(LastName::getContent);

   if (option.isPresent()) {
        strName.append(option.get().get(0));
   }

I would recommend to use the ifPresent option instead, removing the need for your if statement.

Something like:

option.ifPresent(e -> strName.append(option.get().get(0)))
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108