其他东西抛出的异常可以取消异步任务吗?

Can an Exception thrown by something else cancel an async task?

假设我有这个 Java 异步执行某些操作的代码:

public String main() {
    try {
        // Code before that could throw Exceptions

        CompletableFuture.runAsync(() -> {...});

        // Code after that could throw Exceptions
    } catch (SomeException e) {
        // ...
    } catch (CompletionException e) {
        // ...
    }
}

如果这是 运行 并且异步任务成功开始执行,即使其他东西抛出异常,它仍然会完成吗?如果不是,我怎样才能让异步调用在抛出异常时完成执行?

If this were to run and the Async task successfully starts executing, will it still complete even if something else throws an Exception?

是的。任务未中断

注意:如果您的程序因异常而退出,则任务将停止。

If not, how can I let the async call finish executing while the Exception gets thrown?

它默认执行此操作。

如果您想取消任务,它可能会忽略中断。

public String main() {
    CompletableFuture future = null;
    try {
        // Code before that could throw Exceptions

        future = CompletableFuture.runAsync(() -> {...});

        // Code after that could throw Exceptions
    } catch (SomeException e) {
        if (future != null) future.cancel(true);
        // ...
    } catch (CompletionException e) {
        // ...
    }
}

只要任务已经开始,调用runAsync后抛出的任何异常都不会影响该任务。

异常向上传播到调用堆栈。调用堆栈对于特定线程是本地的。由于您的任务 运行 是异步的(即在另一个线程上),因此在另一个线程上抛出的异常无法影响它。