【问题标题】:How to catch exceptions from indirect thread? [duplicate]如何从间接线程中捕获异常? [复制]
【发布时间】:2018-04-09 08:13:34
【问题描述】:

编辑:

How to catch an Exception from a thread - 这不是重复。该链接指的是直接线程(子线程),这里不是这种情况!我们正在谈论间接(孙子线程)。子线程是封闭的JAR(我没有写权限)


我有以下方法:f1 我没有写权限(这是一个封闭的JAR)。

f1 在抛出异常的新线程上创建并运行一个任务。 在main 方法上,我必须在新线程上调用f1。我需要能够捕获从f1 的子线程抛出的所有异常。

换句话说,我如何在不更改son 线程的情况下从grandson 线程捕获异常。

main method opens new thread and call:
      |
      V
f1 method opens new thread and call:
      |
      V
anonymous method which throws exception

示例代码:

private static void f1() {
    Executors.newSingleThreadExecutor()
            .submit(() -> {
                try {
                    throw new Exception("exception from anonymous thread");
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            });

}

public void main() {
    final Future<?> submit = Executors.newSingleThreadExecutor()
            .submit(() -> f1());
    try {
        submit.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • ExecutionException 会将抛出的异常作为根本原因
  • @GhostCat 这不是同一个问题!您的重复是指定向线程(子线程),这里不是这种情况!我们在谈论间接(孙子线程)
  • @GhostCat OP 没有问同样的问题。您的链接是指一个问题,该问题必须对代码进行写访问,而 OP 没有。
  • @ᴳᵁᴵᴰᴼ 我查过了,没有。
  • 没有机会。请记住,当您的 main 方法的 submit.get() 返回时,无法保证由 f1() 生成的异步任务甚至已经完成,更不用说已经传递了一个可检查的异常。甚至链接答案的UncaughtExceptionHandler 也无济于事,因为异常并非没有被发现。当使用submit 时,作业将被包装在一个将捕获任何异常的未来中,因此如果get 被调用,它可以被传播。由于没有人保留对那个未来的引用,所以异常丢失了。不修改f1(),没办法。

标签: java multithreading exception


【解决方案1】:

这个问题没有一般的答案。在这种情况下,异常在 Executor 内部处理。你可以做一个

  • 捕获任务内部可能发生的所有异常,并为捕获的异常返回有意义的状态

  • 如果任务以Callable&lt;?&gt; 提交,则get 返回Future&lt;?&gt; 将抛出ExecutionException 如果任务完成但异常

  • 对于未捕获的异常,您可以在 Executor 使用的线程工厂上设置未捕获的异常处理程序

  • ThreadPoolExecutor 具有afterExecute(Runnable r, Throwable t) 方法,可以处理来自任务的未捕获异常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-26
    • 2010-12-27
    • 2020-03-04
    • 2021-03-05
    • 1970-01-01
    相关资源
    最近更新 更多