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.

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)

Reference

Comments