How to catch exceptions from an indirect thread?

EDIT:

How to catch an exception from a stream is not duplication. The link refers to a direct thread (raw thread), which is not here! We are talking indirect (grandson). The cheese stream is closed JAR(I do not have write access)


I have the following method: f1which I do not have write access to (this is closed JAR).

f1creates and starts the task in a new thread that throws an exception. In the method, mainI have to call f1in a new thread. I need to catch all the exceptions that were thrown from child threads f1.

In other words, how do I catch exceptions from a thread grandsonwithout changing the thread son.

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

Code example:

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();
    }
}
+3
2

. Executor.

  • , , ,

  • ​​ Callable<?>, get Future<?> ExecutionException,

  • Uncaught Exception Handler Thread Factory, Executor

  • ThreadPoolExecutor afterExecute(Runnable r, Throwable t),

+1

ExecutionException, Future::get(), , .

ExecutionException::getCause() , .

0

Source: https://habr.com/ru/post/1695961/


All Articles