首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不从嵌套线程调用默认UncaughtExceptionHandler

不从嵌套线程调用默认UncaughtExceptionHandler
EN

Stack Overflow用户
提问于 2015-02-23 18:04:19
回答 1查看 995关注 0票数 1

我已经阅读了几个如何使用UncaughtExceptionHandler将异常从嵌套线程传递给父线程的示例。目前,我的嵌套线程的UncaughtExceptionHandler按其应有的方式捕获异常。我已经将其设置为将异常传递给父线程的默认UncaughtExceptionHandler.uncaughtException(...)方法。

代码语言:javascript
复制
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是空的,所以我在构造函数中添加了一些逻辑来检查这个值并打印一条消息,但情况似乎并非如此。我也尝试过覆盖父程序的默认异常处理程序,但是没有效果。

我是不是漏掉了什么?对于我来说,我无法理解为什么父母的uncaughtException(...)方法似乎从未被调用过。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-23 18:08:49

代码语言:javascript
复制
public void LoadingThreadExceptionHandler()

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

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

代码语言:javascript
复制
public LoadingThreadExceptionHandler()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28680314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档