【问题标题】:Why Future(Failure(new Exception)) returns Success instead of failure?为什么 Future(Failure(new Exception)) 返回成功而不是失败?
【发布时间】:2020-11-02 13:20:36
【问题描述】:

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

val failure = Future { Failure(new Exception) }

但我得到了

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

谁能回答为什么?

【问题讨论】:

  • 您可以检查failure 的类型是否类似于Future[Try[Nothing]],所以这是一个尝试的未来,在这种情况下我们是一个失败的尝试的成功的未来。请注意,未来的尝试很少有意义。

标签: scala exception future futuretask


【解决方案1】:

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

Future.failed(new Exception)

throw 在未来

Future(throw new Exception)

或致电Future.fromTry

Future.fromTry(Failure(new Exception))

然而

Future(Failure(new Exception))

不代表失败的未来,因为

Failure(new Exception)

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

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

所以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
}

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

【讨论】:

    猜你喜欢
    • 2017-10-13
    • 2015-09-22
    • 1970-01-01
    • 2020-08-15
    • 2014-12-12
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多