CompletableFuture-如何触发异常?

问题描述

这是我的代码:

public void deletevendor(VendorEntity vendorEntity) throws Exception {
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
        try {
            dwService.deleteVendor(vendorEntity);
        } catch (Exception ex) {
            log.info("Error occurred ",ex);
        }
    });
    Boolean isCancelled = future.isCancelled();
    Boolean isDone = future.isDone();
    Boolean isCompletedExceptionally = future.isCompletedExceptionally();

    System.out.println("Asynchronous CompletableFuture: " + isCancelled +" "+ isDone+" "+ isCompletedExceptionally );
}

我在try块中的代码工作正常。我想触发catch块。我怎样才能做到这一点。可以触发我的completablefuture异常的输入是什么?

解决方法

为了进行Future的实验,这是触发catch子句的方式:

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    try {
        throw new Exception("");
    } catch (Exception ex) {
        log.info("Error occurred ",ex);
    }
});

根据您的代码片段,如前所述,整个异常抛出逻辑都在内部调用dwService.deleteVendor(vendorEntity)方法中。这意味着您必须将特定的vendorEntity传递到此public void deletevendor(VendorEntity vendorEntity)方法中,才能引发CompletableFuture中捕获的异常。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...