首页 > 解决方案 > 为什么 Try.recover 中抛出的异常不会中断执行流程?

问题描述

我写了两个函数来说明我的困惑:

import scala.util.Try

def TryRecover: Unit = {
  Try {
    throw new Exception()
  }.recover {
    case e: Exception => {
      println("caught error")
      throw e
    }
  }

  println("got to the end of TryRecover")
}

def tryCatch: Unit = {
  try {
    throw new Exception()
  } catch {
    case e: Exception => {
      println("caught error")
      throw e
    }
  }

  println("got to the end of tryCatch")
}

TryRecover
tryCatch

这是输出:

caught error
got to the end of TryRecover
caught error
java.lang.Exception at .tryCatch(<console>:13) ... 30 elided

我没想到会打印“到 TryRecover 结束”。为什么不中断执行流程throw e.recover

标签: scalaexception

解决方案


Try.recoverpf在另一个 try-catch中执行传入的部分函数参数

  def recover[U >: T](pf: PartialFunction[Throwable, U]): Try[U] = {
    val marker = Statics.pfMarker
    try {
      val v = pf.applyOrElse(exception, (x: Throwable) => marker)
      if (marker ne v.asInstanceOf[AnyRef]) Success(v.asInstanceOf[U]) else this
    } catch { case NonFatal(e) => Failure(e) }
  }

所以因为e被重新抛出pf

{ case e: Exception => println("caught error"); throw e }

recover评估Failure为只是一个普通的一等值的值,也就是说,执行流程没有被破坏。事实上,我们可以说 的主要目的Try是将不安全的异常提升为常规值,这样我们就不会异常崩溃程序。


推荐阅读