When will be an IllegalStateException (unchecked) thrown in Java?

JavaObject Oriented ProgrammingProgramming

An IllegalStateException is an unchecked exception in Java. This exception may arise in our java program mostly if we are dealing with the collection framework of java.util.package. There are many collections like List, Queue, Tree, Map out of which List and Queues (Queue and Deque) to throw this IllegalStateException at particular conditions.

When will be IllegalStateException is thrown

  • An IllegalStateExceptionexception will be thrown, when we try to invoke a particular method at an inappropriate time.
  • In case of java.util.List collection, we use next() method of the ListIterator interface to traverse through the java.util.List. If we call the remove() method of the ListIterator interface before calling the next() method then this exception will be thrown as it will leave the List collection in an unstable state.
  • If we want to modify a particular object we will use the set() method of the ListIterator interface
  • In the case of queues, if we try to add an element to a Queue, then we must ensure that the queue is not full. If this queue is full then we cannot add that element, then it will cause an IllegalStateExceptionexception to be thrown.


Live Demo

import java.util.*;
public class IllegalStateExceptionTest {
   public static void main(String args[]) {
      List list = new LinkedList();
      ListIterator lIterator = list.listIterator();
      lIterator.remove();// modifying the list


Exception in thread "main" java.lang.IllegalStateException
        at java.util.LinkedList$ListItr.set(LinkedList.java:937)
        at IllegalStateExceptionTest.main(IllegalStateExceptionTest.java:15)
Published on 02-Jul-2019 18:22:12