为什么不需要处理可调用接口引发的异常



我有一个这样的代码剪切:

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++;
}
}

我不明白为什么编译器主要不抱怨,因为MyCallable有一个声明为throws Exception的方法。我确信我错过了一些显而易见的东西,但我现在根本看不到。感谢

异常是在一个单独的线程中抛出的,因此您不需要直接在主线程中处理它。如果call()抛出异常,则单独的线程将通过ExecutionException通知您。

你需要明白,如果一个线程因错误而终止,它不会终止主线程或任何其他线程,因为它们是独立的线程。只有当异常在代码本身运行的线程中可丢弃时,处理异常才相关。

最新更新