2010-05-25 11 views

Odpowiedz

37

Rzeczywiście - uważam to za bardzo mylące! Tutaj jest problem, gdzie mam jakąś nieruchomość, która może stanowić parsowalnym data:

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 
      } 

Switching to do postaci funkcjonalnego:

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

W powyższym kodzie, okazuje catching(t) either expr spowoduje Either[T, E] gdzie T jest typem throwable i E jest typem wyrażenia. Następnie można go przekonwertować do określonej wartości za pomocą fold.

Albo jeszcze inna wersja:

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

To może trochę jaśniej - następujący są równoważne:

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

Jeszcze jedna alternatywa: 'failAsValue (classOf [PE]) (nowa data) {parseDate}'. :) – missingfaktor

5

Oto kilka przykładów:

kompilator/Scala/Narzędzia/nsc/interpreter/InteractiveReader.scala

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

kompilatora/Scala/narzędzia/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 
    } 
    } 

kompilator/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 
    } 
+0

czy możesz trochę rozwinąć na przykładzie łowienia ... odwijającego? –