Trevor Trevor - 1 year ago 109
Java Question

What exception to throw - "Wrong Scenario" (Java)

This is a silly question - but it bugs me.

From the existing (library) Java exceptions, which should I throw in the following.

I have a method that is used in the wrong scenario (it's basic assumption doesn't hold).

This method has no arguments - so I tend to skip the


As an example - consider a
class having just two left/right child nodes.

For brevity it's nice to have a
method, which applies only if this node actually has just one child (not 0 or 2).

Obviously if someone calls
on a node
that has 2 children, an exception should be thrown.

Out of the standard Java exceptions - which do you think it should be, and why?

I'm actually going over the list every-once-in-a-while, when this pops-up, and just go with
or with

Answer Source

I have a method that is used in the wrong scenario (it's basic assumption doesn't hold).

That sounds like an exact match for IllegalStateException:

Signals that a method has been invoked at an illegal or inappropriate time.

Admittedly the "time" part feels a little misleading, but given the name it seems reasonable to extend the meaning to "a method has been invoked when the object is in an inappropriate state for that call". Your use is similar to that of Iterator.remove() which throws IllegalStateException if the iterator is before the first element or has already removed the "current" element.

I'd definitely go with that over InternalError which is for Virtual Machine errors, not application code errors.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download