【问题标题】:Scala try/catch vs recover different handing exception in futureScala try/catch vs 在未来恢复不同的处理异常
【发布时间】:2017-10-31 19:13:08
【问题描述】:

有什么区别

try {
       Future . map { }

} catch {}

Future.map {} recover {}

它们不是一回事吗? try catch 如何处理future 中的异常与recover 方法的区别。

【问题讨论】:

标签: scala exception error-handling


【解决方案1】:

当您使用Future 时,您会将结果包装在其中,因此也会包装异常。

这就是为什么这段代码不打印任何东西的原因:

try { Future(throw new RuntimeException(""))} catch { case ex => println("Got it") }

虽然这段代码显示“知道了”:

Future(throw new RuntimeException("")).recover { case ex => println("Got it") }

recoverrecoverWith 方法可帮助您处理包装的异常(如果有)。

【讨论】:

  • 非常感谢先生,这是一个清晰简单的解释
  • recover 和 recoverWith 是否也能处理原始异常而不是包装一个?
  • 不,当您使用返回Future[T] 的函数时,在Future 之外抛出异常是一种不好的做法。你需要尝试/捕捉那些。
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 2011-01-01
  • 2023-03-08
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多