Skip to content

Java IllegalStateException Example

Ramesh Fadatare edited this page Jul 12, 2019 · 1 revision

This Java example demonstrates the usage of java.lang.IllegalStateException class with an 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.

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)
Clone this wiki locally