gpt4 book ai didi

Scala延续和异常处理

转载 作者:行者123 更新时间:2023-12-04 03:23:14 27 4
gpt4 key购买 nike

假设我想捕获一个异常,修复导致异常的问题,然后返回发生异常的同一执行点继续。

如何在Scala中使用延续来实现它?有什么意义吗?

最佳答案

这是实现可恢复错误处理的可能方法之一:

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延续和异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6150331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com