IllegalStateException in Java with Example

This Java example demonstrates the usage of java.lang.IllegalStateException class and when does this exception occurs with a simple example.
IllegalStateException class 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.

What is IllegalStateException? 

The IllegalStateException is a runtime exception thrown to indicate that a method has been invoked at an inappropriate time, or the Java environment or Java application is not in an appropriate state for the requested operation. 

Common Scenarios 

Modifying Collections: Iterating over a collection while simultaneously trying to modify it (without using an iterator's remove method). 

Threads: Calling certain methods before or after a thread has started. 

Java EE: Invoking certain methods when a session has been invalidated or a request has been completed. 

Frameworks and Libraries: Many libraries use IllegalStateException to indicate misuse or incorrect lifecycle operations.

IllegalStateException Class Diagram

Java IllegalStateException Example

In this example, the Iterator.remove() method throws an IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.
package com.javaguides.corejava;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

public class IllegalStateExceptionExample {

    public static void main(String[] args) {

        List < Integer > intList = new ArrayList < > ();

        for (int i = 0; i < 10; i++) {
            intList.add(i);
        }

        Iterator < Integer > intListIterator = intList.iterator(); // Initialized with index at -1

        try {
            intListIterator.remove(); // IllegalStateException
        } catch (IllegalStateException e) {
            System.err.println("IllegalStateException caught!");
            e.printStackTrace();
        }
    }
}
Output:
IllegalStateException caught!
java.lang.IllegalStateException
 at java.util.ArrayList$Itr.remove(ArrayList.java:872)
 at com.javaguides.corejava.IllegalStateExceptionExample.main(IllegalStateExceptionExample.java:21)

Handling IllegalStateException 

Anticipation: Understanding the state model of the objects you're working with can help anticipate potential issues. 

Check Before You Act: Check the state before performing operations. For example, ensure a thread hasn't started before invoking certain methods on it. 

Use Atomic Operations: In concurrent scenarios, ensure that state-changing operations are atomic to prevent inconsistent states. 

Exception Handling: Employ try-catch blocks judiciously to catch and deal with unexpected state violations. 

Best Practices 

  • Be aware of the lifecycle of objects, especially when working with frameworks and libraries. 
  • Clearly document the expected state and constraints for your methods when creating APIs. 
  • Familiarize yourself with Java's concurrency utilities when dealing with multi-threaded applications to avoid state-related issues.

Related Exceptions Posts

Java built-in checked exceptions:
Java built-in unchecked exceptions:
Java built-in errors:

Comments