<分区>
编辑:
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();
}
}