为什么 Future(Failure(new Exception)) 返回成功而不是失败?

Mus*_*pta 3 scala future exception futuretask

我正在尝试以下操作并认为我会失败

val failure = Future { Failure(new Exception) }
Run Code Online (Sandbox Code Playgroud)

但我得到了

Future(Success(Failure(java.lang.Exception)))
Run Code Online (Sandbox Code Playgroud)

谁能回答为什么?

Mar*_*lic 5

Future.failed 可以创造一个失败的未来,例如

Future.failed(new Exception)
Run Code Online (Sandbox Code Playgroud)

throw在未来

Future(throw new Exception)
Run Code Online (Sandbox Code Playgroud)

或打电话 Future.fromTry

Future.fromTry(Failure(new Exception))
Run Code Online (Sandbox Code Playgroud)

然而

Future(Failure(new Exception))
Run Code Online (Sandbox Code Playgroud)

不代表失败的未来,因为

Failure(new Exception)
Run Code Online (Sandbox Code Playgroud)

尽管名称可能具有误导性,但只是一个常规值,例如,

val x = Failure(new Exception)
val y = 42
Future(x)
Future(y)
Run Code Online (Sandbox Code Playgroud)

所以Future(x)是一个成功的未来出于同样的原因Future(y)是一个成功的未来。

您可以将其Future视为一种异步 try-catch,因此如果您没有在 try 中抛出

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

然后 catch 处理程序不会被执行。