IllegalStateException

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.

         Iterator it2 = vect1.iterator();
         while(it2.hasNext())
         {
            Object obj2 = it2.next();
             it2.remove();  
         }

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.

       it1.next();
       it1.remove();       

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

           while(it1.hasNext())
           {
             //  Object obj1 = it1.next();
             it1.remove();
           }

Following code also throws.

    
       while(it1.hasNext())
       {
         Object obj1 = it1.next();
         it1.remove();
         it1.remove();
       }

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.

1 thought on “IllegalStateException”

Leave a Comment

Your email address will not be published.