Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between returning Future.failed(Exception) and throwing an Exception

Tags:

scala

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?

like image 716
jnfr Avatar asked Jul 02 '15 20:07

jnfr


1 Answers

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.

like image 68
Ben Reich Avatar answered Nov 19 '22 20:11

Ben Reich