Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

IllegalStateException

Signals that a method was called at the wrong time — the object is in the wrong state.

Available since: Java 1.1

Syntax

public class IllegalStateException extends RuntimeException

Examples

An order that is already shipped cannot be shipped again:

class Order {
    private boolean shipped;
 
    void ship() {
        if (shipped) throw new IllegalStateException("Order already shipped");
        shipped = true;
        IO.println("Shipped");
    }
}
 
void main() {
    var order = new Order();
    order.ship();
    try {
        order.ship();
    } catch (IllegalStateException e) {
        IO.println(e.getMessage());
    }
}

Output:

Shipped
Order already shipped

Notes

The difference from IllegalArgumentException: there the argument is wrong, here the object's current state is (a stream already closed, an order already paid). The JDK throws it, for example, when a Stream is reused and on a duplicate key in Collectors.toMap().

See also

In the tutorial

  • Custom exceptions — How to create your own exception class in Java — extending Exception or RuntimeException, the message, the cause and extra fields.

Thanks for reading!

Donate to the site — we work hard for you.