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
- Start with A record marked closed
- Do this Try adding a new item
- Result Operation rejected
Syntax
throw new IllegalStateException(message)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaAdd 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.
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());
}
}
}
Order is closed
The payment flag locks the order. The guard runs before the list is modified.
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.
class Main {
public static void main(String[] args) throws Exception {
boolean submitted = true;
System.out.println(submitted ? "Already submitted" : "Send to kitchen");
}
}
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.
Code and output in Java
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");
}
}
}
Change accepted
What to watch for
Use IllegalArgumentException for invalid arguments and IllegalStateException for a valid action attempted at the wrong time.