Java Reference ยท java.lang
IllegalStateException
Reference for IllegalStateException: signal that a method is called at the wrong time, with state-machine examples and how it differs from IllegalArgumentException.
IllegalStateException means a method was called at a time when the object, or the environment, is not in a condition that allows it. The arguments may be perfectly valid; the problem is the state. Reading from a closed scanner, calling next() on an iterator's remove() twice, starting a thread that already started, or adding to a full bounded queue with add() all fall into this category. It extends RuntimeException.
Throw it from your own classes to protect an object's life cycle: "not opened yet", "already closed", "already committed". Callers fix it by changing the order of their calls.
if (closed) { throw new IllegalStateException("connection is closed"); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class IllegalStateException extends RuntimeException
| Constructor | Description |
|---|---|
IllegalStateException() |
No message. |
IllegalStateException(String message) |
Detail message. |
IllegalStateException(String message, Throwable cause) |
Message and cause. |
IllegalStateException(Throwable cause) |
Wraps a cause. |
Usage notes
- State, not arguments. Wrong value passed in:
IllegalArgumentException. Right value, wrong moment:IllegalStateException. - Typical JDK triggers:
Iterator.remove()called twice or beforenext(),Queue.add()on a full bounded queue, a closedScannerorFormatter(these throwIllegalStateException, while closed streams throwIOException),Matcher.group()before a successful match, andStreampipelines used a second time ("stream has already been operated upon or closed"). IllegalThreadStateExceptionis related by name only: it extendsIllegalArgumentException.- Utility classes sometimes throw it from private constructors (
throw new IllegalStateException("utility class")), thoughAssertionErroris also common. - Prefer making illegal states unrepresentable. Use types, builders and immutable objects so the wrong order cannot compile. Where that is impractical, check state at the top of each public method.
- Thread safety. A state check followed by a state change is a race unless both happen under the same lock.
- Optional.
Optional.get()throwsNoSuchElementExceptionfor an empty value, notIllegalStateException. - Do not catch it for control flow. Test a condition (
it.hasNext(),matcher.find()) before acting.