Scala延续和异常处理 [英] Scala continuation and exception handling
本文介绍了Scala延续和异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想抓住一个异常,解决引起异常的问题,并返回到发生异常的同一执行点继续。
Suppose, I would like to catch an exception, fix the problem caused the exception and return to the same execution point where the exception occurred to continue.
如何我在Scala中继续执行它?这是否有意义?
How can I implement it with continuations in Scala? Does it make any sense?
推荐答案
这是实现可恢复错误处理的一种可能方法:
Here is one of the possible ways of implementing resumable error handling:
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))
此代码生成以下输出:
start
Handling error
c:\ttttest true
end Operation finished
这篇关于Scala延续和异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文