EDIT:
How to catch an Exception from a thread - this is not a duplication. The link refers to direct thread (son thread) which it's not the case here! We are talking about indirect (grandson thread). The son thread is a closed JAR (I do not have write access)
I have the following method: f1 which I don't have write access to (It's a closed JAR).
f1 creates and runs a task on new thread which throws exception.
On the main method, I must call f1 on new thread. I need to be able to catch all the exceptions which were thrown from child threads of f1.
In other words, how do I catch exceptions from grandson thread without changing the son thread.
main method opens new thread and call:
|
V
f1 method opens new thread and call:
|
V
anonymous method which throws exception
Example code:
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();
}
}