Library contents

Java IllegalStateException

IllegalStateException signals that an operation is unavailable in the object's current state. The same request may have been valid earlier.

A simple example

IllegalStateException

  1. Start with A record marked closed
  2. Do this Try adding a new item
  3. Result Operation rejected
The same item could be added while the record was open. Its current state prevents the change.

Syntax

Java syntax
throw new IllegalStateException(message)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Add an item after checkout closes

A bakery sends a paid order to the kitchen and locks the ticket. If a second cashier tries to add a pastry, the register needs to explain why the order can no longer change.

ResultOrder is closed
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        boolean paid = true;
        var order = new java.util.ArrayList<String>();
        try {
            if (paid) throw new IllegalStateException("Order is closed");
            order.add("Pastry");
        } catch (IllegalStateException closed) {
            System.out.println(closed.getMessage());
        }
    }
}
Output
Order is closed

The payment flag locks the order. The guard runs before the list is modified.

Advertisements

Send a draft only once

A caterer marks each order as submitted after it leaves the counter. When the send button is pressed again, a state check prevents a second kitchen ticket.

ResultAlready submitted
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        boolean submitted = true;
        System.out.println(submitted ? "Already submitted" : "Send to kitchen");
    }
}
Output
Already submitted

Checking the state before issuing the ticket makes the action safe to repeat in this single-threaded example.

Edit a draft outing

An organizer adds a stop while the trip is still a draft. Allow a change only while the booking is open. A closed booking requires a separate amendment.

GivenOpen draft
Worked resultChange accepted
Code and output in Java
Java source
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;

class Main {
    public static void main(String[] args) throws Exception {
        try {
            boolean closed=false;
            if(closed) throw new IllegalStateException("closed");
            System.out.println("Change accepted");
        } catch (IllegalStateException problem) {
            System.out.println("Start amendment");
        }
    }
}
Output
Change accepted

What to watch for

Use IllegalArgumentException for invalid arguments and IllegalStateException for a valid action attempted at the wrong time.

Documentation for IllegalStateException