Java Exception Handling

Java Exception Handling – IllegalStateException

Today we make our way to the IllegalStateException in Java, as we continue our journey through Java Exception Handling series. The “proper” use of the IllegalStateException class is somewhat subjective, since the official documentation simply states that such an exception “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.”

Throughout the rest of this article we’ll explore the IllegalStateException in greater detail, starting with where it resides in the overall Java Exception Hierarchy. We’ll also look at a couple functional code samples that illustrate how IllegalStateExceptions are used in built-in Java APIs, as well as how you might throw IllegalStateExceptions in your own code, so let’s get started!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

As mentioned, the properly using the IllegalStateException class is really a matter of personal taste and opinion. For me, I feel it’s best used when attempting to manipulate an object instance in such a way that doesn’t make sense. For example, an application that implements the state design pattern would contain objects that track some internal state of being, such as a field value. When this object is in a particular state, it may be illogical to allow calling/execution of certain methods. In such cases, an IllegalStateException is, in my opinion, the ideal exception to throw.

To illustrate in code we have two unique examples. The first example we’ll go over uses our own Book class and explicitly throwing an IllegalStateException:

The first critical method for this code example is the Book(String title, String author, Integer pageCount, Date publishedAt) constructor, which allows calling code to pass in a publication date:

The other important method is publish(), which checks if a publication date already exists, in which case it throws a new IllegalStateException indicating that the book cannot be published a second time:

This is simple logic, but it illustrates how you might go about using the IllegalStateException in your own code. Here, we’ve made the decision to disallow calling publish() for a Book that has already been published. Arguably, we could opt to ignore this issue and only perform publish() logic when getPublishedAt() returns null. In this case, however, our business logic requires throwing an exception instead.

The code to test this out consists of creating two unique Book instances, one with a publication date and one without, and then attempting to publish() them through the publishBook(Book book) method:

Executing this code produces the following output:

As desired, attempting to publish the previously-published A Game of Thrones Book results in an IllegalStateException, while the instance representing this very article doesn’t have a publication date, so publishing it works just fine.

In addition to using IllegalStateException in your own custom code, these exceptions are also used throughout the codebase of other modules and libraries, including the JDK API. For example, we can reuse a bit of the code from our previous Java Exception Handling - ConnectException article, which attempts to connect to a provided URL and outputs the results:

The critical addition is within the connectionTest() method, where we attempt to invoke the setIfModifiedSince(long ifmodifiedsince) method after we’ve already established a connection. The source code of the class shows that this throws an IllegalStateException, since we’ve already established a connection (and, therefore, setting this field makes no sense):

Sure enough, executing the connectionTest() method successfully connects, but then throws an IllegalStateException when invoking setIfModifiedSince(long ifmodifiedsince):

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring, Maven, log4j, Struts, Kotlin, Grails, Groovy, and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!