I’d like to throw an exception in a method that is expecting a list that only has one element, and I’d like to throw an exception if the list has more than one. I am trying to determine if there is an appropriate existing Java exception to throw for this case. I tried eyeballing the list here but didn’t see anything that jumped out as correct.
In this case I am calling a method of an object, with the expectation that the method is referencing said list as an attribute of the object. So I am actually not passing the array, nor an index as an argument.
(edited for clarification)
Since you are trying to imply that given input is not a valid one you should use
IllegalArgumentExceptionwith a message stating the reason for the same.Or else you can have your own
Exceptionwhich uniquely defines the condition.Though I somehow feel since its the number of elements which is the reason for exception you can even use
IndexOutOfBoundsExceptionwhich makes sense in the given scenario.Edit: As per comment
Given that list is not part of method call but belongs to the object whose method is invoked, in this case
list.size() > 1signifies that object is not in a correct state and with that a customized version ofIllegalStateExceptionorIllegalStateExceptionitself with a proper error message would be more appropriate.