我已经阅读了几个如何使用 anUncaughtExceptionHandler
将异常从嵌套线程传递到父线程的示例。目前,我的嵌套线程UncaughtExceptionHandler
应该捕获异常。我已将其设置为将异常传递给父线程的默认UncaughtExceptionHandler.uncaughtException(...)
方法。
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;
}
运行它会产生以下输出:
这是嵌套线程的处理程序
无论出于何种原因,调用了 nested UncaughtExceptionHandler
,但它似乎没有将异常传递给父线程的 default UncaughtExceptionHandler
,因为在那之后没有任何反应。我曾一度怀疑父母的默认值可能UncaughtExceptionHandler
是 null 所以,我在构造函数中添加了一些逻辑来检查这一点并打印一条消息,但情况似乎并非如此。我也尝试过覆盖父级的默认异常处理程序,但无济于事。
我在这里错过了什么吗?对于我的一生,我无法理解为什么uncaughtException(...)
似乎从未调用过父母的方法。