BackendBench
Coffee

Home โ€บ Java exceptions โ€บ IllegalStateException

Unchecked exception ยท java.lang

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 committed

Extends 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

How to fix it

  1. Find which object is in the wrong state; the message and stack trace name it.
  2. Reorder calls so the setup happens before the use, and close resources only once.
  3. For response-committed errors, make sure only one place writes the response and that you return after redirecting or sending an error.
  4. Use try-with-resources so lifecycle is handled by the language.

Broken and fixed

fails
Scanner in = new Scanner(System.in);
in.close();
in.nextLine(); // IllegalStateException: Scanner closed
works
try (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.

Related exceptions

More tools you might need