Would you throw an IllegalStateException
if:
- A method is unable to do its job because of the value(s) of one or more fields
- Those fields are
final
and assigned only in the constructor?
Textbook example: your class is an immutable Collection<BigInteger>
and your method is supposed to return the maximum element, but this instance is empty.
I have read Kevin Bourillon`s blog post on the subject and I am not sure which rule applies.
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.
Definitely not. Many instances of this class are not empty and the operation would have succeeded.
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.
Not quite. This instance was constructed with zero length, so this instance is not and could never have been non-empty.
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.
Might apply if the parameter in question is the implicit this
parameter. This is the exception I am tempted to throw, but I am concerned that it could be confusing.
Update: changed example from Collection<Integer>
to Collection<BigInteger>
because the fact that there was an identity element (Integer.MIN_VALUE
) distracts from the question.