O'Reilly logo

Java Threads, Second Edition by Henry Wong, Scott Oaks

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The ThreadDeath Class

The ThreadDeath class is a special Throwable class that is used to stop a thread. This class extends the Error class and hence should not be caught by the program. In theory, there is no reason to catch and handle any Throwable object that is not an object of the Exception class, and that usually applies to the ThreadDeath class as well.

How does throwing an object actually stop a thread? As we mentioned, the thread cleans up after itself when the run() method completes. Of course, there are two ways for the run() method to complete: it can complete on its own by simply returning, or it can throw or fail to catch an exception (including an Error or Throwable object).

By default, if the run() method throws an exception, the thread prints an error message, along with the stack trace of the exception. However, a special case is made for the ThreadDeath object. If a ThreadDeath object is thrown from the run() method, the uncaughtException() method simply returns.

The ThreadDeath object is normally used only in conjunction with the stop() method. When you call the stop() method on a particular thread, a ThreadDeath object is created and then thrown by the target thread. Since the stop() method is deprecated, the utility of this technique is minimal.

Is it possible to catch the ThreadDeath object? It is possible to catch any Throwable object; however, it is not advisable to use this technique to prevent the death of the thread. After all, if we did not want the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required