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

java – 何时为构造函数抛出异常

发布时间:2020-12-15 04:10:19 所属栏目:Java 来源:网络整理
导读:public Neocortex(Region rootRegion,ConnectionInterface functor) {this.rootRegion = rootRegion;this.currentRegion = this.rootRegion;this.functor = functor;} 嘿上面我有一个类的构造函数.我的问题是我应该在构造函数中添加空指针异常还是不必要?老
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;
}

解决方法

嗯……这是一个品味问题.

如果类的前提条件是必须提供rootRegion,那么保护类实现不需要在整个地方进行空检查是有意义的.

因此,回答“何时应该在构造函数中抛出异常”的问题:我会在所有情况下执行此操作,其中来自使用者的参数使您的实现处于无效状态,委托问题(即抛出异常).

如果你试图将角色作为消费者一段时间,并且你选择不进行空检查,他将拥有如下代码:

Neocortex n = new Neocortex(null,null);
n.doSomeething();

如果他到达第二行,并且这里的实现抛出NullPointerException,那么他将不清楚它是由于他提供的参数.

(编辑:李大同)

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

    推荐文章
      热点阅读