Java 完全的未来和例外-这里缺少什么?
当我试图理解异常的Java 完全的未来和例外-这里缺少什么?,java,exception,java-8,completable-future,Java,Exception,Java 8,Completable Future,当我试图理解异常的功能时,我读了一些和,但我不明白这段代码有什么问题: public CompletableFuture<String> divideByZero(){ int x = 5 / 0; return CompletableFuture.completedFuture("hi there"); } 但结果总是: 线程“main”java.lang.arithmetricException中的异常:/by零 调用divideByZero()时,代码int
功能时,我读了一些和,但我不明白这段代码有什么问题:
public CompletableFuture<String> divideByZero(){
int x = 5 / 0;
return CompletableFuture.completedFuture("hi there");
}
但结果总是:
线程“main”java.lang.arithmetricException中的异常:/by零
调用divideByZero()
时,代码intx=5/0
立即在调用方的线程中运行,这解释了它失败的原因,正如您所描述的(在创建CompletableFuture
对象之前就会引发异常)
如果希望在将来的任务中运行零除法,则可能需要将该方法更改为以下内容:
public static CompletableFuture<String> divideByZero() {
return CompletableFuture.supplyAsync(() -> {
int x = 5 / 0;
return "hi there";
});
}
publicstaticcompletablefuture除以零(){
返回CompletableFuture.SupplySync(()->{
int x=5/0;
返回“你好”;
});
}
它以线程“main”java.util.concurrent.ExecutionException:java.lang.ArrithmeticException:/by zero中的异常结束
(由java.lang.ArrithmeticException:/by zero引起)如果此块可能抛出异常public CompletableFuture divideByZero(){int x=5/0;返回CompletableFuture.completedFuture(“hi there”);}
public static CompletableFuture<String> divideByZero() {
return CompletableFuture.supplyAsync(() -> {
int x = 5 / 0;
return "hi there";
});
}