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 ...
Get Java Threads, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.