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.

e.g.

(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();
t.start();
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();
l.add(“Ram”);
l.add(“Shyam”);
l.add(“Kiran”);
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();
	    t.start();
	    System.out.println("Thread Started");
	    t.start();
	    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(Thread.java:708)
	at com.masterjavatutorial.TestExample.main(TestExample.java:7)

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