This question already has an answer here:
- Null check chain vs catching NullPointerException 19 answers
I have a complex model structure in my project.
Sometimes I have to get a deep placed value from it. It looks like following:
something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
The problem is that each of those methods could return null
, and I will get NullPointerException
in case if it does.
What I want to know is should I write long if like
if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
//process getFourthSomething result.
}
Or it is OK just to use try..catch like following:
SomethingFourth fourth = null;
try {
fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }
if(fourth != null) {
///work with fourth
}
I know that NPE
is a thing to be avoided, but isn't it overhead to avoid it in my case?