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

前端之家收集整理的这篇文章主要介绍了java – IllegalStateException是否适用于不可变对象?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果出现以下情况,您会抛出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在这里是合适的.如果构造正确(即“它已经太晚了”部分),该实例可能处于正确的状态.

猜你在找的Java相关文章