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



In this article, we will learn how an IllegalStateException (unchecked) is thrown in Java. IllegalStateException is a subclass of RuntimeException. It occurs when a method is used at the wrong time or when an object is not in the right state.

What is an IllegalStateException?

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, such as List, Queue, Tree, and Map, of which List and Queues (Queue and Deque) throw this IllegalStateException under particular conditions.

When will an IllegalStateException be thrown?

An IllegalStateException exception will be thrown when we try to invoke a particular method at an inappropriate time. The following are some cases that throw an IllegalStateException:

ListIterator - Calling remove() before next()

In case of java.util.List collection, we use the 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.

List<String> list = new ArrayList<>();
list.add("Tutorials");
list.add("Point");
ListIterator<String> iterator = list.listIterator();
iterator.remove();

It will throw an IllegalStateException as no current element to remove from the list.
Correct way:

iterator.next();    // Moves to first element
iterator.remove();  

If we want to modify a particular object, we will use the set() method of the ListIterator interface:

ListIterator<String> iterator = list.listIterator();
iterator.next();         
iterator.set("Point");

Queue - Adding to a full queue

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 an element, then it will cause an IllegalStateException exception to be thrown.

Queue<String> queue = new ArrayBlockingQueue<>(2);
queue.add("Item1");
queue.add("Item2");
queue.add("Item3");

Fixed-size queue of capacity 2 will throw an IllegalStateException as the queue is full after the second insertion.

StringBuilder and StringBuffer

Modifying a StringBuilder or StringBuffer after converting it to a String will throw this exception.

StringBuilder sb = new StringBuilder("Hello");
String s = sb.toString();
sb.append("Tutorials Point");

This will throw an IllegalStateException as we are trying to modify a StringBuilder after converting.

How to Handle IllegalStateException

Handling the IllegalStateException exception cases when it might occur:

Check Object State Before Operations

To prevent IllegalStateException, always verify the state of an object before executing important operations. Use appropriate getter methods or state checks to ensure the object is in the expected condition.
For example:

if (!mySession.isOpen()) {
    throw new IllegalStateException("Session must be open before performing this action.");
}

Log & Handle carefully

If you get an IllegalStateException in production code, log it for examination but also resolve it carefully so that the application does not crash. Provide a user-friendly error message or take alternative actions when possible.

For example:
try {
    // Perform operation that may throw IllegalStateException
} catch (IllegalStateException e) {
    log.error("Illegal state exception occurred: ", e);
    response.sendError(500, "Internal Server Error: Please try again later.");
}

Example of an IllegalStateException

Below is an example to demonstrate the IllegalStateException exception in Java:

import java.util.*;
public class IllegalStateExceptionTest {
   public static void main(String args[]) {
      List list = new LinkedList();
      list.add("Welcome");
      list.add("to");
      list.add("Tutorials");
      list.add("Point");
      ListIterator lIterator = list.listIterator();
      lIterator.next();
      lIterator.remove();// modifying the list
      lIterator.set("Tutorix");
      System.out.println(list);
   }
}

Output

Exception in thread "main" java.lang.IllegalStateException
        at java.util.LinkedList$ListItr.set(LinkedList.java:937)
        at IllegalStateExceptionTest.main(IllegalStateExceptionTest.java:15)
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-05-06T18:38:52+05:30

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements