Mic*_*ael 10 continuations scala exception-handling
假设,我想捕获异常,修复导致异常的问题并返回到发生异常的同一执行点继续.
如何在Scala中使用continuation实现它?它有意义吗?
ten*_*shi 11
以下是实现可恢复错误处理的可能方法之一:
import java.io.File
import java.lang.IllegalStateException
import scala.util.continuations._
// how it works
ctry {
println("start")
val operationResult = someOperation(new File("c:\\ttttest"))
println("end " + operationResult)
} ccatch {
case (DirNotExists(dir), resume) =>
println("Handling error")
dir.mkdirs()
resume()
}
def someOperation(dir: File) = {
cthrow(DirNotExists(dir))
println(dir.getAbsolutePath + " " + dir.exists)
"Operation finished"
}
// exceptions
trait CException
case class DirNotExists(file: File) extends CException
// ctry/ccatch classes and methods
sealed trait CTryResult[T] {
def get: T
def ccatch(fn: PartialFunction[(CException, () => T), T]): T
}
case class COk[T](value: T) extends CTryResult[T] {
def ccatch(fn: PartialFunction[(CException, () => T), T]) = value
def get = value
}
case class CProblem[T](e: CException, k: Any => Any) extends CTryResult[T] {
def ccatch(fn: PartialFunction[(CException, () => T), T]) =
fn((e, () => k(Unit).asInstanceOf[T]))
def get = throw new IllegalStateException("Exception was not processed: " + e)
}
def ctry[T](body: => T @cps[Any]) = reset (body) match {
case (e: CException, k: (Any => Any)) => CProblem[T](e, k)
case value => COk(value)
}
def cthrow(e: CException): Any @cps[Any] = shift((k: Any => Any) => (e, k))
Run Code Online (Sandbox Code Playgroud)
此代码生成以下输出:
start
Handling error
c:\ttttest true
end Operation finished
Run Code Online (Sandbox Code Playgroud)