3

I was trying the following and thinking that I'll get a failure

val failure = Future { Failure(new Exception) }

but instead I got

Future(Success(Failure(java.lang.Exception)))

Can anyone answer why?

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • You can check that the type of `failure` is something like **Future[Try[Nothing]]**, so it is a future of a try, in this case us a successful future of a failed try. Note that, a future of a try rarely makes sense. – Luis Miguel Mejía Suárez Jul 13 '20 at 13:12

1 Answers1

5

Future.failed can create a failed future, for example

Future.failed(new Exception)

or throw inside the future

Future(throw new Exception)

or call Future.fromTry

Future.fromTry(Failure(new Exception))

however

Future(Failure(new Exception))

does not represent a failed future because

Failure(new Exception)

is, despite possibly misleading names, just a regular value, for example,

val x = Failure(new Exception)
val y = 42
Future(x)
Future(y)

so Future(x) is a successful future for the same reason Future(y) is a successful future.

You can think of Future as a kind of async try-catch, so if you are not throwing inside the try

try {
  Failure(new Exception) // this is not a throw expression
} catch {
  case exception =>      // so exception handler does not get executed
}

then catch handler does not get executed.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98