This came up in a discussion with a colleague today.
The Javadocs for Java's IllegalStateException
state that it:
Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
And Effective Java says (Item 60, page 248):
Another commonly reused exception is IllegalStateException. This is generally the exception to throw if the invocation is illegal because of the state of the receiving object. For example, this would be the exception to throw if the caller attempted to use some object before it had been properly initialized.
It seems there's a bit of discrepancy here. The second sentence of the javadocs makes it sound like the exception could describe a very broad condition about the Java execution state, but the description in Effective Java makes it sound like it's used for conditions related specifically to the state of the state of the object whose method has been called.
The usages I've seen in the JDK (e.g. collections, Matcher
) and in Guava definitely seem to fall into the category that Effective Java talks about ("This object is in a state where this method can't be called"). This also seems consistent with IllegalStateException
's sibling IllegalArgumentException
.
Are there any legitimate IllegalStateException
usages in the JDK that do relate to the "Java environment" or "Java application"? Or do any best practices guides advocate using it for the broader execution state? If not, why the heck are the javadocs phrased like that? ;)