Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is IllegalStateException appropriate for an immutable object?

Tags:

java

exception

Would you throw an IllegalStateException if:

  1. A method is unable to do its job because of the value(s) of one or more fields
  2. 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.

like image 276
finnw Avatar asked Jul 16 '10 18:07

finnw


2 Answers

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.

like image 161
Jon Avatar answered Sep 21 '22 15:09

Jon


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).

like image 44
Eric Petroelje Avatar answered Sep 18 '22 15:09

Eric Petroelje