1

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

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

For brevity it's nice to have a removeOnlyChild() method, which applies only if this node actually has just one child (not 0 or 2).
Obviously if someone calls n.removeOnlyChild() on a node n 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 IllegalStateException or with InternalError.

5
  • 1
    I would create my own custom Exception-derived class and throw that. This way you will know exactly why it is being thrown. Commented Dec 2, 2013 at 22:29
  • Is it wise to have such a method in the first place? Shouldn't you have removeLeft(), removeRight() and removeAll()? Do you at least have a childCount() method allowing the caller to check that he can safely call removeOnlyChild() before calling it? Commented Dec 2, 2013 at 22:32
  • 1
    In general, you should not throw InternalError or any other subclass of Error unless you have a good reason to do so. By design, subclasses of Error won't be caught by ... } catch (Exception ex) { ... Commented Dec 2, 2013 at 22:36
  • @JB yes of-course I have childCount() for the user to tread safely. This is however, a bit more general, as to what to throw when an assumption isn't met when calling a method. Commented Dec 2, 2013 at 23:46
  • Similar: What exception to throw when a property or a method being accessed is temporarily unavailable? Commented May 23, 2017 at 4:36

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Sound like the right thing :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.