Monday, 4 April 2011

Core Java: Exceptions in Java Thread

When the main thread in a single-threaded application throws an uncaught exception, you are likely to notice because the stack trace is printed on the console (and because the program stops).
By invoking stat() method another thread is started, but the run() method is not really the "main" method of the new thread. The run() method is executed inside a context that allows the virtual machine to handle runtime exceptions thrown from the run() method.
All uncaught exceptions are handled by code outside of the run() method before the thread terminates. The default exception handler is a Java method; it can be overridden. This means that it is possible for a program to write a new default exception handler.
The default exception handler is the uncaughtException() method of the ThreadGroup class. It is called only when an exception is thrown from the run() method. The default implementation of the uncaughtException() method is to print out the stack trace of the Throwable object thrown by the run() method (if it is not an object of ThreadDeath class).


Moreover that the basic Thread Exception classes are:

  1. java.lang.IllegalThreadStateException (unchecked exception class): Thrown to indicate that a thread is not in an appropriate state for the requested operation.
  2. java.lang.ThreadDeath (unchecked exception class): It is a sub-class Error (in general programmer should not try to handle them). An instance of ThreadDeath is thrown in the victim thread when the stop method with zero arguments in class Thread is called. An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.
  3. java.lang.InterruptedException (checked exception class): Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

No comments:

Post a Comment