3

I am looking at a code base where the domain model consists of many nested member variables.

Consider this scenario

private static String getSomeStringRepresentation(A input) {
    String result = "";
    try {
         result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
    } catch (NullPointerException e) {
        Logger.logDebug(e.getMessage());
    }
    return result;
}

In this call chain, any method call can result in a NullPointerException. Is it correct to handle it with a catch clause in this case? Is this a case where "it is possible to handle the exception" ?

Edit

The case of checking for null four times is really ugly. Don't you consider catching the NPE is justified in this case?

The problem here is calling some method on a object that possibly could be null.

H.Rabiee
  • 4,747
  • 3
  • 23
  • 35
  • If all methods could throw an NullPointerException, why would it be incorrect not to use a try-catch case? – akluth Apr 26 '13 at 07:59

4 Answers4

4

Why don't you check for null rather than putting a catch block? Catching NullPointerException isn't considered good practice.

If catching null pointer exception is not a good practice, is catching exception a good one?

also

Is Catching a Null Pointer Exception a Code Smell?

Community
  • 1
  • 1
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

Catching a NullPointerException is not a good practice without a serious reason: Rather check for null object like this:

private static String getSomeStringRepresentation(A input) {
    String result = "";
    try {
         if(input != null && input.getTypeA() != null && input.getTypeA().getTypeAInfo() != null && getTypeAInfo().get(0) != null){
              result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();     
         }

    } catch (NullPointerException e) {
        Logger.logDebug(e.getMessage());
    }
    return result;
}

Here is a possible duplicate on the subject.

Community
  • 1
  • 1
javadev
  • 1,639
  • 2
  • 17
  • 35
1

NPEs are just an error in the code and should therefore not be catched - they should be fixed.

LionC
  • 3,106
  • 1
  • 22
  • 31
0

NullPointerException indicates a programming error, catching it is wrong. Instead of catching it fix bugs in your program.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275