As the name indicates, this exception is thrown when the programmer is doing an operation that is illegal at the present moment (but legal at some other time or context). That is, in appropriate time a method is called, the JVM throws this exception. Examples for IllegalStateException are many in Java. Let us explain with an example of java.util.Iterator used to iterate and remove elements from a data structure.

Following is the hierarchy.

Object –> Throwable –> Exception –> RuntimeException –> IllegalStateException

(All the above exception classes are from java.lang package)

Observe the following code.

The next() method of Iterator places the cursor on the element to return. If remove() method is called, the element where the cursor is positioned is removed. If remove() method is called without calling next() method, which element is to be removed by the JVM because cursor will be pointing no element. At this point calling remove() is an illegal operation. But calling next() and afterwards remove() is a legal operation.

Now let us go further.

The remove() and set() operations are dependency operations and depend on next() method. Calling remove() and set() methods without calling next() method is an error.

The above code works fine. But calling it1.remove() without calling is an exception. The following code throws IllegalStateException.

Following code also throws.

The first remove() method removes the element pointed by next() method. If the element is removed, the second remove() method removes which element because next() is not called thereby no element is pointed by the cursor to remove.

One thought on “IllegalStateException

Leave a Reply

Your email address will not be published. Required fields are marked *