为什么下面的代码仍会抛出异常,即使它正由onFailure
处理val f: Future[Int] = Future {
Thread.sleep(10)
1/0
1
}
f.onComplete {
case Success(value) => println(value)
case Failure(ex)=> println(ex)
}
Await.result(f, Duration.Inf) // throws an Arithmetic exception
答案 0 :(得分:2)
因为onComplete
被注册为未来的回调,它不会改变它或产生新的未来。这意味着你有效地等待未来会引发异常。
您想使用recover/recoverWith
:
val f: Future[Int] = Future {
Thread.sleep(10)
1/0
1
}
val recovered: Future[Int] = f.recover { case e: ArithmeticException => 0 }
Await.result(recovered, Duration.Inf)