Back Button
Back to Chapter
Introduction
No items found.
Collapse_Icon
Table of Contents

Exception:

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program. Exceptions are objects that represent errors that may occur in a Java program.

Java run system will throw IllegalThreadStateException whenever we attempt to invoke a method that a thread cannot handle in the given state. For example, a sleeping thread cannot deal with the resume() method because a sleeping thread cannot receive any instructions. The same is true with the suspend() method when it is used on a blocked (Not Runnable) thread.

Whenever we call a thread method that is likely to throw an exception, we have to supply an appropriate exception handler to catch it. The catch statement may take one of the following forms.

catch (ThreadDeath e)
{.....................
.....................     // killed the thread
}
catch (InterruptedException e)
{.....................
.....................     // cannot handle it in the current state
}
catch (Illegal ArgumentException e)
{.....................
.....................     //illegal method argument
}
catch (Exception e)
{.....................
.....................     // Any other
}

Example:

public class Demo extends Thread
{
  public static void main(String args[])
  {
      Demo d1 = new Demo();
      d1.start();
      d1.start();
  }
}

Output: