我写了两个函数来说明我的困惑:
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
Run Code Online (Sandbox Code Playgroud)
这是输出:
caught error
got to the end of TryRecover
caught error
java.lang.Exception at .tryCatch(<console>:13) ... 30 elided
Run Code Online (Sandbox Code Playgroud)
我没想到会打印“到了 TryRecover 的结尾”。为什么throw e在.recover不中断运行的流动?
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) }
}
Run Code Online (Sandbox Code Playgroud)
所以因为e被重新抛出pf
{ case e: Exception => println("caught error"); throw e }
Run Code Online (Sandbox Code Playgroud)
recover求Failure值到value 只是一个常规的一流值,即执行流程没有中断。事实上,我们可以说 的主要目的Try是将不安全的异常提升为常规值,这样我们就不会异常崩溃程序。
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |