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

In Scala, what is the difference between returning Future.failed(new Exception("message!")) And throw new Exception("message!") ?

Let's say this happens in a function that should return Future[Unit] , and the calling function looks like this:

 someFunction onFailure { case ex: Exception => log("Some exception was thrown") } 

Is there a preference for one over the other or a specific use case for each?

+7
scala
source share
1 answer

Calling Future { throw ex } and Future.failed(ex) will produce an equivalent result. However, using Future.failed 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 expected) it depends on the try...catch . As you know, they have heavy overhead compared to regular code. The Future.failed method is essentially a shortcut to this, without the expense of actually throwing an exception.

+8
source share

All Articles