gpt4 book ai didi

java - 未从嵌套线程调用默认 UncaughtExceptionHandler

转载 作者:行者123 更新时间:2023-11-30 03:32:31 26 4
gpt4 key购买 nike

我已经阅读了几个如何使用 UncaughtExceptionHandler 将异常从嵌套线程传递到父线程的示例。目前,我的嵌套线程的 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;
}

运行此命令会产生以下输出:

This is the nested thread's handler

无论出于何种原因,都会调用嵌套的 UncaughtExceptionHandler ,但它似乎没有将异常传递给父线程的默认 UncaughtExceptionHandler ,因为在那之后什么也没有发生。我曾经一度怀疑父级的默认 UncaughtExceptionHandler 可能为 null,因此,我在构造函数中添加了一些逻辑来检查这一点并打印一条消息,但情况似乎并非如此。我也尝试覆盖父级的默认异常处理程序,但没有成功。

我在这里遗漏了什么吗?我一生都无法理解为什么父级的 uncaughtException(...) 方法似乎从未被调用。

最佳答案

public void LoadingThreadExceptionHandler()

这没有被调用,因为它不是构造函数。当您调用 new LoadingThreadExceptionHandler() 时,将调用无参数默认构造函数(如果不存在构造函数,则由编译器创建)。

要修复它,它应该没有返回类型:

public LoadingThreadExceptionHandler()

关于java - 未从嵌套线程调用默认 UncaughtExceptionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28680314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com