IllegalStateException in Java — What It Means and How to Fix It

What Java's IllegalStateException means and how to fix it.

Published November 2, 2026

IllegalStateException is thrown when a method is called at an inappropriate time, because the object is not in the right state for that operation.

What it means and why it happens

Examples: using a closed stream, calling next() twice on an iterator remove, or using a builder before it is configured.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
java.lang.IllegalStateException: Not connected

Practical examples

Code that triggers it

conn.send(data);   // before connect()

The fix

if (!conn.isConnected()) throw new IllegalStateException("Not connected");
conn.send(data);

Fix the call order

conn.connect();
conn.send(data);
conn.close();

Common mistakes

  • Calling methods in the wrong order.
  • Reusing closed resources.
  • Ignoring lifecycle docs.

Key takeaways

  • IllegalStateException: IllegalStateException is thrown when a method is called at an inappropriate time, because the object is not in the right state for that operation.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Which resources throw it?

Streams, scanners, iterators and many framework lifecycle objects.

How do I find which line caused IllegalStateException?

The error message and stack trace show the file and line; start there and work backwards.

More Java articles