Would you throw an IllegalStateException
if:
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.
It doesn't sound like any of the common exception classes you mention above fit into the Textbook example.
You should throw a NoSuchElementException
as that's exactly what the Collections.max()
method does.
I think IllegalStateException
is appropriate here. The instance could have been in the correct state, if it was constructed correctly (i.e. the "it's already too late" part).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With