微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/java/128229.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐