IllegalStateException: Detecting Invalid Object States
What you'll learn: You'll learn how to recognize when an object cannot perform an operation because it's in the wrong state, and how IllegalStateException signals this problem.
The Core Idea
An IllegalStateException is an unchecked exception that indicates an object is not in an appropriate state to execute a requested operation. Think of it like trying to withdraw money from a bank account that's already closed—the account object exists, but it's in a state where withdrawals don't make sense.
Unlike IllegalArgumentException, which flags bad inputs, IllegalStateException flags problems with the object's internal condition at the time of the method call.
Common Scenarios
Calling methods in the wrong order:
class FileProcessor {
private boolean isOpen = false;
public void open() {
isOpen = true;
}
public void processData() {
if (!isOpen) {
throw new IllegalStateException("Cannot process data: file not open");
}
// process the file
}
}
Object lifecycle violations:
class Connection {
private boolean closed = false;
public void send(String message) {
if (closed) {
throw new IllegalStateException("Connection is closed");
}
// send message
}
public void close() {
closed = true;
}
}
When to Throw IllegalStateException
Throw this exception when:
- An object's state prevents it from performing the requested operation
- The caller made a valid request, but at the wrong time
- The sequence of operations violated the object's contract
Real-World Analogy
It's like trying to drive a car that's out of gas. The request (drive) is valid, but the car's state (empty tank) prevents the operation.
Key Takeaway: Use IllegalStateException to enforce that methods are called only when the object is in a valid state to handle them, catching lifecycle and sequencing errors at runtime.