I've read through several examples of how to use an UncaughtExceptionHandler
to pass exceptions from a nested thread to a parent thread. Currently, my nested thread's UncaughtExceptionHandler
catches exceptions as it should. I've set it to pass exceptions to the parent thread's default UncaughtExceptionHandler.uncaughtException(...)
method.
public void load() {
// Create the nested thread
final Thread loadingThread = new Thread(new Runnable() {
@Override
public void run() {
// Do stuff... throw an exception at some point
throw new RuntimeException("Something has gone horribly wrong!");
}
}
});
// Set up a custom exception handler for the nested thread
class LoadingThreadExceptionHandler implements UncaughtExceptionHandler {
// The parent exception handler
private UncaughtExceptionHandler defaultHandler;
// Constructor to get a handle on the parent's exception handler
public void LoadingThreadExceptionHandler() {
// Check if the parent thread has an exception handler
if (Thread.getDefaultUncaughtExceptionHandler() == null) {
System.out.println("The default handler is null");
}
// Get the parent's default exception handler
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
return;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.prinln("This is the nested thread's handler");
// Pass it onto the parent's default exception handler
defaultHandler.uncaughtException(t, e);
}
};
// Set the custom exception handler on the loadingThread
loadingThread.setUncaughtExceptionHandler(new LoadingThreadExceptionHandler());
// Start the thread
loadingThread.start();
return;
}
Running this produces the following output:
This is the nested thread's handler
For whatever reason, the nested UncaughtExceptionHandler
is called, but it doesn't seem to pass the exception to the parent thread's default UncaughtExceptionHandler
, as nothing happens after that point. I did at one point suspect maybe the parent's default UncaughtExceptionHandler
was null so, I added some logic in the constructor to check for this and print a message, but this doesn't seem to ever be the case. I've also attempted overriding the parent's default exception handler as well, although to no avail.
Am I missing something here? I cannot, for the life of me, understand why the parent's uncaughtException(...)
method never seems to be called.
public void LoadingThreadExceptionHandler()
This is not being called, because it's not the constructor. When you invoked new LoadingThreadExceptionHandler()
, the no-arg default constructor (which is created by the compiler if no constructor exists) is invoked.
To fix it, it should be without a return type:
public LoadingThreadExceptionHandler()