How to resolve IllegalStateException in Java?
An exception is an unwanted and unexpected error thrown in the program. Most of the time, an exception occurs when there is an error in our code but it can be handled. It disrupts the normal flow of the code.
For example, the code throws an exception if the user has entered invalid information, if the code is unable to read the file located at the remote place, or if the network connection is lost in the middle of the communication.
IllegalStateException in Java
IllegalStateExceptionis the sub-class of RuntimeException class, and therefore it is an unchecked exception. It is raised by the programmer or by the API developer explicitly. It is thrown when a method call illegal or a method is called at incorrect time.
For example, once we start a thread, we cannot restart the same thread again; if we try to do that, it throws a runtime exception i.e., IllegalStateException.
The exception may arise in the code usually when we are working with the Collections framework. The List, Queue, Maps, Tree are some of the collections. Out of these, List and Queues tend to throw the illegal state exception at the specific conditions.
Note: IllegalStateException exception is not just limited to the Collections framework.
Let's see some of the scenario where the IllegalStateException will be thrown.
The following Java program depicts the situation where we try to call the start() method when the run() method is already executing.
The following code depicts the situation where we call the start() method on a thread when the execution of run() method is over.
The following code explains the situation where we are using the remove() method to remove the element from the ArrayList, before moving to the first element.
Solution for the IllegalStateException
To avoid the java.lang.IllegalStateException in Java we should take care that any method in our code cannot be called at inappropriate or illegal time.
Solution for example 1 and 2:
Consider the above example 1 and 2 where we have called the start() method more than once. If we call it only once, we will not get this exception. Because start() method is not called after starting the thread.
Solution for Example 3:
The remove() method of the ArrayList class is used to remove the last element after calling the next() method.
In order to prevent the exception we need to follow the above steps in our Java code.