你知道 Apache Commons Validate 的一些不错的替代品吗?或 Guava Preconditions在检查对象是否为 not null(Spring Assert 除外)时会抛出 IllegalArgumentException 而不是 NullPointerException?
我知道 Javadocs说:
Applications should throw instances of this class [NullPointerException] to indicate other illegal uses of the null object.
不过,我就是不喜欢它。对我来说,NPE 总是意味着我只是忘了在某处保护空引用。我的眼睛训练有素,我可以发现它以每秒几页的速度浏览日志,如果我这样做,我的脑海中总会启用错误警报。因此,将它抛到我期望 IllegalArgumentException 的地方会让我感到很困惑。
假设我有一个 bean :
public class Person {
private String name;
private String phone;
//....
}
和服务方式:
public void call(Person person) {
//assert person.getPhone() != null
//....
}
在某些情况下,一个人没有电话(我的祖母没有电话)可能没问题。但是,如果您想调用这样的人,对我来说就是调用 call 方法并传递一个 IllegalArgument。查看层次结构 - NullPointerException 甚至不是 IllegalArgumentException 的子类。它基本上告诉您 - 您再次尝试在空引用上调用 getter。
此外,已经进行了讨论并且有this我完全支持的好答案。所以我的问题只是 - 我是否需要做这样丑陋的事情:
Validate.isTrue(person.getPhone() != null, "Can't call a person that hasn't got a phone");
按照我的方式进行,或者是否有一个库会抛出 IllegalArgumentException 以进行 notNull 检查?
最佳答案
由于这个问题的主题演变为“IllegalArgumentException和NullpointerException的正确用法”,我想指出Effective Java Item 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.
关于java - 先决条件库为 notNull 检查抛出 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30038924/