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

java – IllegalStateException是否适用于不可变对象?

发布时间:2020-12-15 02:55:27 所属栏目:Java 来源:网络整理
导读:如果出现以下情况,您会抛出IllegalStateException: 由于一个或多个字段的值,方法无法完成其工作 那些字段是最终的,只在构造函数中分配? 教科书示例:您的类是一个不可变的集合 BigInteger并且您的方法应该返回最大元素,但此实例为空. 我已经阅读了有关该主
如果出现以下情况,您会抛出IllegalStateException:

>由于一个或多个字段的值,方法无法完成其工作
>那些字段是最终的,只在构造函数中分配?

教科书示例:您的类是一个不可变的集合< BigInteger>并且您的方法应该返回最大元素,但此实例为空.

我已经阅读了有关该主题的Kevin Bourillon`s blog post,我不确定适用哪条规则.

UnsupportedOperationException – this means that the method invoked will always fail for an instance of this class (concrete type),regardless of how the instance was constructed.

当然不.此类的许多实例都不为空,操作也会成功.

IllegalStateException – … there does exist at least one alternate state that the instance in question could have been in,which would have passed the check … <snip> … Note also that this exception is appropriate whether or not it is possible to actually mutate this aspect of the instance’s state,or it’s already too late.

不完全的.这个实例是用零长度构造的,所以这个实例不是,也永远不会是非空的.

IllegalArgumentException – throwing this exception implies that there exists at least one other value for this parameter that would have caused the check in question to pass.

如果相关参数是隐含的此参数,则可以应用.这是我很想抛出的例外,但我担心它可能会令人困惑.

更新:已从Collection< Integer>更改示例收集< BigInteger>因为存在标识元素(Integer.MIN_VALUE)的事实会分散注意力.

解决方法

我认为IllegalStateException在这里是合适的.如果构造正确(即“它已经太晚了”部分),该实例可能处于正确的状态.

(编辑:李大同)

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

    推荐文章
      热点阅读