提问者:小点点

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块。我该怎么做。可以触发我的完全未来异常的输入是什么?


共1个答案

匿名用户

为了对< code>Future进行实验,这是您触发< code>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 vendor实体)method中,以便抛出在