使用scala.util.control.Exception

使用scala.util.control.Exception,scala,scala-2.8,Scala,Scala 2.8,有人有使用()的好例子吗?我正努力从这些类型中找出答案 的确如此——我也觉得这很令人困惑!这里有一个问题,我有一些属性可能是可解析的日期: 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.E

有人有使用()的好例子吗?我正努力从这些类型中找出答案

的确如此——我也觉得这很令人困惑!这里有一个问题,我有一些属性可能是可解析的日期:

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(_) ) 
在上面的代码中,旋转
捕捉(t)或expr
将导致
或[t,E]
其中
t
是可丢弃的类型,
E
是表达式的类型。然后可以通过
折叠将其转换为特定值

或另一个版本:

val date =
     handling(classOf[PE]) by (_ => new Date) apply parseDate
这也许更清楚一点——以下是等效的:

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

以下是一些例子:

编译器/scala/tools/nsc/InteractiveReader.scala

  def readLine(prompt: String): String = {
    def handler: Catcher[String] = {
      case e: IOException if restartSystemCall(e) => readLine(prompt)
    }
    catching(handler) { readOneLine(prompt) }
  }
编译器/scala/tools/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
    }
  }
编译器/scala/tools/nsc/io/Process.scala

  def exitValue(): Option[Int] =
    catching(classOf[IllegalThreadStateException]) opt process.exitValue()
library/scala/xml/include/sax/Main.scala

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

...

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

还有一种选择:
failAsValue(classOf[PE])(新日期){parseDate}
:)你能详细介绍一下“捕获…展开”的例子吗?