Getting rid of NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE?

我的未来我决定 提交于 2020-01-15 07:03:18

问题


I'm getting NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE in this snippet

final Integer id = Ints.tryParse(idString);
FailReason.NO_SUCH_THING.checkCondition(id!=null);
something.setId(id.intValue());

Here, checkCondition works just like Preconditions.checkArgument except for it throws my own exception. Throwing NPE or IAE is not appropriate here, as it's checking an external input rather than a programming error.

FindBugs complains that "The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed."

Can I teach FindBugs that checkCondition never returns normally when the argument is false?


回答1:


I (sort of) solved it by adding

assert id!=null;

It's redundant and ugly, but still less ugly than @SuppressFBWarnings and more local.




回答2:


Try using java.util.Objects.requireNonNull to please FindBugs:

final Integer id = Ints.tryParse(idString);
FailReason.NO_SUCH_THING.checkCondition(id!=null);
something.setId(Objects.requireNonNull(id).intValue());

Or you might be able to use java.util.Objects.isNull to fool FindBugs.

final Integer id = Ints.tryParse(idString);
FailReason.NO_SUCH_THING.checkCondition(!Objects.isNull(id));
something.setId(id.intValue());


来源:https://stackoverflow.com/questions/23746395/getting-rid-of-np-null-on-some-path-from-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!