public Neocortex(Region rootRegion, ConnectionInterface functor) {
this.rootRegion = rootRegion;
this.currentRegion = this.rootRegion;
this.functor = functor;
}
你好,上方是我一个类的构造函数。我的问题是,我是否应该在构造函数中添加空指针异常,或者这样做是否不必要?说实话,我并不明白何时应该在代码中添加异常。但是,在这种情况下,我应该使用哪个构造函数呢?
public Neocortex(Region rootRegion, ConnectionInterface functor) {
if (rootRegion == null) {
throw new NullPointerException("rootRegion cannot be null");
} else if (functor == null) {
throw new NullPointerException("functor cannot be null");
}
this.rootRegion = rootRegion;
this.currentRegion = this.rootRegion;
this.functor = functor;
}
IllegalArgumentException
更清晰。我总是认为如果抛出NullPointerException
,那么就是取消引用了null
。 - rgettmanGetNextItem
方法的队列当没有更多数据存在时可能不允许将空引用入队,但不会期望对传入的项进行解引用)。在后一种情况下抛出NPE将是意外的,但在前一种情况下则不是那么意外。 - supercat