8. Threads and Exceptions
Threads and exceptions
A thread will be terminated if it meets an uncaught exception. The uncaught exception is usually the sign of a serious error, their
occurrence needs to be tracked in some way. To enable this, every thread can have associated with it an instance of UncaughtExceptionHandler
which has a method:
public void uncaughtException(Thread thr, Throwable exc);
that can handle the exception, and the thread throws exception.
When the thread meets an uncaught exception. Following will happen.
- Get
UncaughtExceptionHandlerhandler of the thread, which can be set throughsetUncaughtExceptionHandlerand calluncaughtException()/ - If the handler is not set, the
ThreadGroupof the thread is returned, in this caseuncaughtException()will be called on the handler of thatThreadGroupor its father groups.- In case no parent
ThreadGrouphas the handler, handler will be taken from the static methodThread.getdefaultUncaughtExceptionHandler - In case
Thread.getdefaultUncaughtExceptionHandlerreturns nothing, the stack trace will of the exception will be printed.
- If thread is terminated before
getUncaughtExceptionHandleris called, the method will returnnull.
Therefore, you can control the handling of uncaught exceptions, by:
- At the system level, by setting a default handler using the static Thread class method setDefaultUncaughtExceptionHandler. This operation is security checked to ensure the application has permission to control this.
- At the group level, by extending ThreadGroup and overriding it’s definition of uncaughtException.
- At the thread level, by invoking setUncaughtExceptionHandler on that thread.
Therefore, if there is something that make your code not print uncaught exceptions of the thread, look at its handler.
Don’t call stop()
Like interrupt, Thread.stop() is used for terminate thread, there are several differences:
- The thread throws
ThreadDepthexception, unlikeinterruptwhich assign a flag on the current thread. - The terminated thread will release the lock immediately when it is executing the code in synchronized block.
This causes several issues:
- If methods on the upper stack catch the exception and then not rethrow, the code will be malicious.
- As it aborts immediately in the synchronized block, the code can corrupt when just partially complete the current operation.
So don’t use stop().