java线程池submit如何捕获异常

  • A+
所属分类:Java

如果您不想使用future.get()来获取任务的结果,并希望在提交任务时捕获异常,可以使用CompletableFuture结合handle()exceptionally()方法来实现。

下面是一个示例代码,演示如何使用CompletableFuture捕获异常:

ExecutorService executor = Executors.newFixedThreadPool(10);

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // 在这里执行任务
    // 抛出异常
    throw new RuntimeException("Exception in task");
}, executor);

future.handle((result, ex) -> {
    if (ex != null) {
        System.out.println("Exception in task: " + ex.getMessage());
    }
    return null;
});

executor.shutdown();

在上面的代码中,我们使用CompletableFuture.runAsync()方法提交一个任务,它返回一个CompletableFuture<Void>对象。然后,我们使用handle()方法注册一个处理函数,该函数将在任务完成或抛出异常时被调用。

在处理函数中,我们检查ex参数是否为null,如果不为null,则表示任务抛出了异常,我们可以在此处进行异常处理。

另一种替代方案是使用exceptionally()方法,它与handle()方法类似,但只处理异常情况。下面是使用exceptionally()方法的示例代码:

ExecutorService executor = Executors.newFixedThreadPool(10);

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // 在这里执行任务
    // 抛出异常
    throw new RuntimeException("Exception in task");
}, executor);

future.exceptionally(ex -> {
    System.out.println("Exception in task: " + ex.getMessage());
    return null;
});

executor.shutdown();

在这种情况下,exceptionally()方法注册的处理函数只会在任务抛出异常时被调用,可以在此处进行异常处理逻辑。

请注意,在使用CompletableFuture时,需要确保最终调用线程池shutdown()方法来关闭线程池,以避免资源泄漏。

ZPY

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: