In Scala, what's the difference between returning Future.failed(new Exception("message!"))
and throw new Exception("message!")
?
Let's say this is happening in a function that is to return Future[Unit]
, and the calling function is like so:
someFunction onFailure {
case ex: Exception => log("Some exception was thrown")
}
Is there a preference of one over the other or a specific use case for each?
Calling Future { throw ex }
and Future.failed(ex)
will create an equivalent result. However, using Future.failed
is more efficient. If we look at this snippet from Future.apply
(from here in the source):
promise complete {
try Success(body) catch { case NonFatal(e) => Failure(e) }
}
We notice that (as could be expected), this relies on a try...catch
block. These are known to carry heavy overhead when compared to normal code. The Future.failed
method is essentially a shortcut to this without having to incur the cost of actually ever throwing the exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With