Home โบ Java exceptions โบ IllegalStateException
IllegalStateException: causes and fixes
A method was called at a time when the object was not in a state that allows it.
What it looks like
java.lang.IllegalStateException: Cannot call sendError() after the response has been committedExtends RuntimeException in java.lang.
What it means
The arguments may be fine, but the object is not ready for this call: a closed resource used again, an iterator advanced after the end, a response modified after it was sent, a builder used before it is configured. Frameworks use it heavily to report wrong ordering or lifecycle mistakes, so the message is often the most useful part.
Common causes
- Using a resource after it was closed, such as a Scanner, a stream or a database connection.
- A servlet or controller writing to the response after it was already committed, often after an earlier error handler.
- Calling
Iterator.remove()twice or beforenext(). - Spring context problems: "Failed to load ApplicationContext", or a bean accessed while the context is shutting down.
How to fix it
- Find which object is in the wrong state; the message and stack trace name it.
- Reorder calls so the setup happens before the use, and close resources only once.
- For response-committed errors, make sure only one place writes the response and that you return after redirecting or sending an error.
- Use try-with-resources so lifecycle is handled by the language.
Broken and fixed
Scanner in = new Scanner(System.in);
in.close();
in.nextLine(); // IllegalStateException: Scanner closedtry (Scanner in = new Scanner(System.in)) {
String line = in.nextLine();
}๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
"Failed to load ApplicationContext" in tests wraps the real cause deeper in the trace; scroll to the last Caused by line. Use the stack trace beautifier to find it quickly.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is IllegalStateException a checked or unchecked exception?
IllegalStateException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is IllegalStateException in?
It lives in java.lang, so the import is import java.lang.IllegalStateException; (java.lang needs no import).
What is the first thing to check when I see IllegalStateException?
Read the message and the first stack trace line in your own code. The usual causes are: Using a resource after it was closed, such as a Scanner, a stream or a database connection; and A servlet or controller writing to the response after it was already committed, often after an earlier error handler.