scala - 为什么 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
解决方案
Try.recover
pf
在另一个 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
是将不安全的异常提升为常规值,这样我们就不会异常崩溃程序。
推荐阅读
- javascript - 尝试根据输入是否具有文本 node.js 车把来隐藏/显示部分内容
- python - 如何获取字典值的频率并映射到所有潜在值的固定顺序?
- c# - C# System.Threading.Mutex System.Threading.Mutex.OpenExisting 方法未找到
- sql - 每行的 SQL 动态 WHERE 子句
- javascript - 我可以使用 JavaScript 的 fetch() 函数从 file.php 调用特定方法吗?
- angular - Angular10 - 等待第一行完成
- angular - 将 2 个 firebase 集合合并到一个数组中
- system-verilog - 在函数中放置工厂注册时出现空项错误
- cmake - 无法在调试构建配置中使用 assimp 库
- java - com.google.firebase.database.Query 无法转换为 com.google.firebase.database.DatabaseReference