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

问题描述 投票:1回答:1

我有这样的代码截图:

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

我不明白为什么编译器不会在main中抱怨,因为MyCallable有一个声明为throws Exception的方法。我敢肯定,我在这里遗漏了一些明显的东西,但是我现在看不到它。谢谢

java exception callable
1个回答
2
投票

该异常在单独的线程中抛出,因此您无需直接在主线程中处理它。如果call()引发异常,则单独的线程将通过ExecutionException通知您。

您需要了解,如果线程由于错误而终止,它不会终止主线程或任何其他线程,因为它们是分开的线程。仅当异常可在代码本身运行的线程内引发时,处理异常才有意义。

© www.soinside.com 2019 - 2024. All rights reserved.