IllegalStateException vs UnsupportedOperationException

MonsterHunter :

I'm confusing of using exception: IllegalStateException vs UnsupportedOperationException.

I have a delete method which in some cases do not allow to use: let's say when the caller has a valid data on it.

Then I should give an exception info to user that he is doing an invalid operation now.

So, which exception should I throw? IllegalStateException or UnsupportedOperationException.

I know I can give the detail message using any of them, but I still want to know which one is better in my case.

From JavaDoc:

  • IllegalStateException:

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

  • UnsupportedOperationException:

Thrown to indicate that the requested operation is not supported.

davidxxx :

UnsupportedOperationException should be used as the method is not supported at all while IllegalStateException should be used as the method is supported but that in the current state, it is not legal.

The Iterator classes are good candidates to illustrate the difference between these two exceptions.

Iterator implements remove() in a default method by throwing a UnsupportedOperationException :

public interface Iterator<E> {
    ...
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
    ...
}

The method is indeed never supported by implementations that don't override this method to support it.

About implementations, we can see that the Iterator implementation used by the ArrayList class overrides remove() to support it. So UnsupportedOperationException is not thrown any longer.

On the other hand, we can also see that the method throws an IllegalStateException if you invoke it while you never invoked next() to make progress the iterator to the next element :

private class Itr implements Iterator<E> {
    ...
    public void remove() {      
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    ...
    }
}

The method is so supported by this implementation but if you invoke it in a illegal state, an IllegalStateException is thrown.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=443735&siteId=1