How to Solve java.lang.IllegalStateException in Java main Thread?
An unexpected, unwanted event that disturbed the normal flow of a program is called Exception.
Most of the time exception is caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating in U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.
There are mainly two types of exception in java as follows:
1. Checked Exception:
The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exception then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get compile-time error.
Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc.
2. Unchecked Exception:
The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception.
Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException etc.
Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.
IllegalStateException is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise explicitly by programmer or by the API developer to indicate that a method has been invoked at the wrong time. Generally, this method is used to indicate a method is called at an illegal or inappropriate time.
Example: After starting a thread we are not allowed to restart the same thread once again otherwise we will get Runtime Exception saying IllegalStateException.
Example 1: We call start() method when it’s already executing the run() method.
Example 2: We call start() method on a thread when it has finished executing run() method.
How to solve this error?
In order to avoid java.lang.IllegalStateException in Java main Thread we must ensure that any method in our code cannot be called at an illegal or an inappropriate time.
In the above example if we call start() method only once on thread t then we will not get any java.lang.IllegalStateException because we are not calling the start() method after the starting of thread (i.e we are not calling the start() method at an illegal or an inappropriate time.)