加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Preconditions库为notNull检查抛出IllegalArgumentExcep

发布时间:2020-12-14 05:56:30 所属栏目:Java 来源:网络整理
导读:你知道 Apache Commons Validate或 Guava Preconditions的一个不错的替代品,当检查对象是否为空( Spring Assert除外)时会抛出IllegalArgumentException而不是NullPointerException吗? 我知道Javadocs说: Applications should throw instances of this clas
你知道 Apache Commons Validate或 Guava Preconditions的一个不错的替代品,当检查对象是否为空( Spring Assert除外)时会抛出IllegalArgumentException而不是NullPointerException吗?

我知道Javadocs说:

Applications should throw instances of this class [NullPointerException] to indicate other
illegal uses of the null object.

不过,我只是不喜欢它.对我来说,NPE总是意味着我只是忘了在某个地方获得null引用.我的眼睛是如此受过训练,我可以发现它以每秒几页的速度浏览日志,如果我这样做,那么我的头脑中始终会启用bug警报.因此,如果将它抛到我期望IllegalArgumentException的位置,那将是非常令人困惑的.

说我有一个豆子:

public class Person {
  private String name;
  private String phone;
  //....
}

和服务方法:

public void call(Person person) {
  //assert person.getPhone() != null
  //....
}

在某些情况下,一个人没有电话可能没问题(我的奶奶不拥有任何电话).但是如果你想打电话给这样的人,对我而言,它会调用带有IllegalArgument的调用方法.查看层次结构 – NullPointerException甚至不是IllegalArgumentException的子类.它基本上告诉你 – 再次尝试在null引用上调用getter.

此外,已经有讨论,我完全支持this很好的答案.所以我的问题只是 – 我是否需要像这样做丑陋的事情:

Validate.isTrue(person.getPhone() != null,"Can't call a person that hasn't got a phone");

有我的方式,或者是否有一个库只会抛出IllegalArgumentException进行notNull检查?

解决方法

由于这个问题的主题演变为“正确使用IllegalArgumentException和NullpointerException”,我想指出有效Java项目60(第二版)中的海峡前瞻性答案:

Arguably,all erroneous method invocations boil down to an illegal argument
or illegal state,but other exceptions are standardly used for certain kinds of illegal
arguments and states. If a caller passes null in some parameter for which null values are prohibited,convention dictates that NullPointerException be thrown rather than IllegalArgumentException. Similarly,if a caller passes an out-ofrange value in a parameter representing an index into a sequence,IndexOutOfBoundsException should be thrown rather than IllegalArgumentException.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读