Java – is it a bad style to use NullPointerException to test null?

I have some code along the following pattern:

return a().b().c().d().e();

Now, since each of these methods can return null, we usually test:

if( (a()!=null) && (a().b() != null) && ....) {
   return a().b().c().d().e();
} else  {
  return null;
}

(and some local variables may be used to avoid repeated calls)

I'd love to:

try {
   return a().b().c().d().e();
} catch (NullPointerException e) {
   return null;
}

Is this considered a bad style? inefficiency? It's still good

Solution

Don't do this. Throwing and catching exceptions is quite expensive compared to basic null checking

You may also be interested to know that this syntax is proposed for future versions of Java, which will make it easier It will look like this:

a()?.b()?.c()?.d()

“?” The action will be "." Optional version of Operator If LHS is empty, it will return null instead of trying to evaluate RHS It's exactly what you're looking for, but I'm afraid I didn't cut for Java 7 I don't know the status of this function in Java 8

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>