我知道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检查?
解决方法
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.