Scala延续和异常处理
发布时间:2020-12-16 19:10:23 所属栏目:安全 来源:网络整理
导读:假设我想捕获一个异常,修复引起异常的问题,并返回到发生异常的同一执行点继续. 如何在Scala中继续执行它?有什么意义吗? 解决方法 以下是实现可恢复错误处理的可能方法之一: import java.io.Fileimport java.lang.IllegalStateExceptionimport scala.util.
假设我想捕获一个异常,修复引起异常的问题,并返回到发生异常的同一执行点继续.
如何在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]) = value def get = value } case class CProblem[T](e: CException,k: Any => Any) extends CTryResult[T] { def ccatch(fn: PartialFunction[(CException,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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |