使用scala.util.control.Exception

时间:2010-05-25 09:37:35

标签: scala scala-2.8

有没有人使用scala.util.control.Exception version 2.12.0version 2.8.0)的好例子?我正在努力从类型中弄明白。

2 个答案:

答案 0 :(得分:37)

确实 - 我也觉得它很混乱!这是一个问题,我有一些属性,可能是一个可解析的日期:

def parse(s: String) : Date = new SimpleDateFormat("yyyy-MM-dd").parse(s)
def parseDate = parse(System.getProperty("foo.bar"))

type PE = ParseException
import scala.util.control.Exception._

val d1 = try { 
             parseDate
           } catch { 
             case e: PE => new Date
           }

将其切换为功能形式:

val date =
     catching(classOf[PE]) either parseDate fold (_ => new Date, identity(_) ) 

在上面的代码中,转为catching(t) either expr会产生Either[T, E],其中T是throwable的类型,E是表达式的类型。然后可以通过fold将其转换为特定值。

或者是另一个版本:

val date =
     handling(classOf[PE]) by (_ => new Date) apply parseDate

这可能更清楚一点 - 以下是等同的:

handling(t) by g apply f 
try { f } catch { case _ : t => g }

答案 1 :(得分:5)

以下是一些例子:

编译器/阶/工具/ NSC /解释器/ InteractiveReader.scala

  def readLine(prompt: String): String = {
    def handler: Catcher[String] = {
      case e: IOException if restartSystemCall(e) => readLine(prompt)
    }
    catching(handler) { readOneLine(prompt) }
  }

编译器/阶/工具/ NSC / Interpreter.scala

  /** We turn off the binding to accomodate ticket #2817 */
  def onErr: Catcher[(String, Boolean)] = {
    case t: Throwable if bindLastException =>
      withoutBindingLastException {
        quietBind("lastException", "java.lang.Throwable", t)
        (stringFromWriter(t.printStackTrace(_)), false)
      }
  }

  catching(onErr) {
    unwrapping(wrapperExceptions: _*) {
      (resultValMethod.invoke(loadedResultObject).toString, true)
    }
  }

...

  /** Temporarily be quiet */
  def beQuietDuring[T](operation: => T): T = {
    val wasPrinting = printResults
    ultimately(printResults = wasPrinting) {
      printResults = false
      operation
    }
  }

  /** whether to bind the lastException variable */
  private var bindLastException = true

  /** Temporarily stop binding lastException */
  def withoutBindingLastException[T](operation: => T): T = {
    val wasBinding = bindLastException
    ultimately(bindLastException = wasBinding) {
      bindLastException = false
      operation
    }
  }

编译器/阶/工具/ NSC / IO / Process.scala

  def exitValue(): Option[Int] =
    catching(classOf[IllegalThreadStateException]) opt process.exitValue()

库/阶/ XML /包含/萨克斯/ Main.scala

def saxe[T](body: => T) = catching[T](classOf[SAXException]) opt body

...

   ignoring(classOf[SAXException]) {
     includer.setProperty(lexicalHandler, s)
     s setFilter includer
   }