IllegalStateException in Java

      No Comments on IllegalStateException in Java

IllegalStateException occurs when a method is invoked at an inappropriate time. It is thrown by JVM at runtime.


(1.) Suppose a thread is started and again if you call start() method again to restart the same thread, it would give IllegalStateException.

Thread t = new Thread();
System.out.println(“Thread Started”);
t.start(); // throws IllegalStateException

(2.) In the below example, remove() method is being called at an inappropriate time.
List l = new ArrayList();
Iterator iterator = l.iterator();
iterator.remove(); // throws IllegalStateException

Hierarchy of IllegalStateException:

Object —> Throwable —> Exception —> RuntimeException —> IllegalStateException

So, IllegalStateException is a child class of RuntimeException. All child classes of RuntimeException are unchecked exceptions.

Hence, IllegalStateException is unchecked exception.

Demo Examples:

package com.masterjavatutorial;
public class TestExample {
	public static void main(String[] args){
	    Thread t = new Thread();
	    System.out.println("Thread Started");
	    System.out.println("Thread restarted");

Output of the above program is as below:

Thread Started
Exception in thread "main" java.lang.IllegalThreadStateException
	at java.lang.Thread.start(
	at com.masterjavatutorial.TestExample.main(

It can be seen from the above output that calling start() method second time throws IllegalThreadStateException.