Why is not needed to handle Exception throw by Callable interface

Adrian :

I have a code sniping like this:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UserManagementApplication {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService es = Executors.newSingleThreadExecutor();
        MyCallable callable = new MyCallable(10);
        MyThread thread = new MyThread(10);
        System.out.println(es.submit(callable).get());
        System.out.println(es.submit(thread).get());
        es.shutdown();
    }
}

class MyCallable implements Callable<Integer> {
    private Integer i;

    public MyCallable(Integer i) {
        this.i = i;
    }

    @Override
    public Integer call() throws Exception {
        return --i;
    }
}

class MyThread extends Thread {
    private int i;

    MyThread(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        i++;
    }
}

I don't understand why the compiler does not complain in main because MyCallable has a method that is declared as throws Exception. I am sure that I am missing something obvious here but simply I can't see it right now. Thanks

akuzminykh :

The exception is thrown in a seperate thread so you don't need to handle it directly in the main thread. If call() throws an exception the seperated thread will let you know over the ExecutionException.

You need to understand that if a thread terminates due to an error it does not terminate the main thread, or any other thread, because they are seperated threads. Handling exceptions is only relevant when the exception is throwable within the thread the code is running in itself.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16567&siteId=1