Exception Handling in Threads
09 Jan 2017
By contract, Runnable#run method does not allow throwing exceptions. Possible ways of handling exceptions are
try/catch blocks or setting
exception handler on thread or thread group.
A thread or thread group allows us to set an exception handler on it, to receive exceptions occured during the execution of thread.
How it works
If you are clever enough, following flowchart says it all. Have a look!
Create a general
ExceptionalThread class which inherits from
Thread and generates
ArrayIndexOutOfBoundsException when run. See the code below
Inherit 3 more classes from this class with names
ThreadSpecificHandler thread sets its
UncaughtExceptionHandler and exception will be caught in this handler.
ThreadGroupHandler thread calls
uncaughtException method of its thread group.
DefaultHandler thread calls
DefaultUncaughtExceptionHandler of the thread.
Code for all three classes is given below