I have multiple methods running concurrently on different threads. If an exception occurs and isn't handled on any of the threads, I want it to propagate back to the calling method (see example below).
public class Main {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.execute(new Thread1Class());//Thread 1 of many
//...
}
}
class Thread1Class implements Runnable{
@Override
public void run() {
try {
throw new InterruptedException(); //How do I propogate this to the main method?
} catch (InterruptedException e) {
System.out.println("An unchecked exception was caught here");
}
}
}
The threads must implement Runnable since Callable will block the threads from running concurrently.
I followed the method of Overriding protected void afterExecute(Runnable r, Throwable t)
shown as the accepted answer here: Handling exceptions from Java ExecutorService tasks. If I understand correct, this solution will only handle unchecked exceptions. How should I deal with the checked exceptions?
CodePudding user response:
If I understand correct, this solution will only handle unchecked exceptions. How should I deal with the checked exceptions
No, the afterExecute(Runnable, Throwable) would catch any RuntimeException or checked exception. According to the docs at https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html
If non-null, the Throwable is the uncaught RuntimeException or Error that caused execution to terminate abruptly.
Edit:
Sorry for the misunderstanding,
If you want to propagate the checked exception to the caller, you would need to wrap it in a RuntimeException
InterruptedException a;
throw new RuntimeException("wrapped", a);
The executor:
protected void afterExecute(Runnable r, Throwable t){
Throwable root = t.getCause();
}
Or you could create your own runtime exception type.