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 RuntimeExceptionExamples
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 shippedNotes
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
- IllegalArgumentException — Signals that a method received an invalid argument.
- UnsupportedOperationException — Thrown when an operation is not supported by the object, such as changing an unmodifiable collection.
- RuntimeException — The base class of unchecked exceptions — bugs in program logic.
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.