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在这里是合适的.如果构造正确(即“它已经太晚了”部分),该实例可能处于正确的状态.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...