Scala continuation and exception handling

后端 未结 3 1950
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 16:03

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.

How ca

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-14 16:22

    This function should do it (place the code that throws exceptions at foo arg):

    def F[T](foo: => T, dealWithError: Exception => T): T =
      try foo
      catch{
        case ex: Exception => dealWithError(ex)}
    

    I use these class + implicit conversion:

      class ORfoo[R](foo: () => R){
        def or(r: R): R =
          try foo() 
          catch{
            case ex: Exception => r
          }
        }
    

    implicit def ORfooWrapper[R](f: => R) = new ORfoo(() => f)

    It allows you python-like exception treatment, like "1a".toInt or 5

提交回复
热议问题