【问题标题】:Default UncaughtExceptionHandler not being called from nested thread未从嵌套线程调用默认 UncaughtExceptionHandler
【发布时间】:2015-02-23 18:04:19
【问题描述】:

我已经阅读了几个如何使用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;
}

运行它会产生以下输出:

这是嵌套线程的处理程序

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

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

【问题讨论】:

  • 你期望什么输出?

标签: java multithreading uncaughtexceptionhandler


【解决方案1】:
public void LoadingThreadExceptionHandler()

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

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

public LoadingThreadExceptionHandler()

【讨论】:

  • 哦,哇,我不敢相信我犯了这么小的错误!删除返回类型确实使它工作。谢谢!
  • @AnnaW 我很高兴能帮上忙。我认为大多数 IDE 会显示警告,指出方法名称与类名称相同。
猜你喜欢
  • 1970-01-01
  • 2011-12-08
  • 2020-06-01
  • 2015-07-27
  • 1970-01-01
  • 2020-12-07
  • 2014-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多