Sometimes the computation in a Future can create an exception, which will cause the Future to fail. In the "Creating a Future" example, what if the calling code passed 55
and 0
to the divide
method? It'd throw an ArithmeticException
after trying to divide by zero, of course. How would that be handled in consuming code? There are actually a handful of ways to deal with failures.
Handle the exception with recover
and pattern matching.
object Calculator {
def calculateAndReport(a: Int, b: Int) = {
val eventualQuotient = FutureDivider divide(a, b)
eventualQuotient recover {
case ex: ArithmeticException => println(s"It failed with: ${ex.getMessage}")
}
}
}
Handle the exception with the failed
projection, where the exception becomes the value of the Future:
object Calculator {
def calculateAndReport(a: Int, b: Int) = {
val eventualQuotient = FutureDivider divide(a, b)
// Note the use of the dot operator to get the failed projection and map it.
eventualQuotient.failed.map {
ex => println(s"It failed with: ${ex.getMessage}")
}
}
}