有没有人使用scala.util.control.Exception版本2.12.0(版本2.8.0)的好例子?我正在努力从类型中弄明白.
oxb*_*kes 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
}
Run Code Online (Sandbox Code Playgroud)
将其切换为功能形式:
val date =
catching(classOf[PE]) either parseDate fold (_ => new Date, identity(_) )
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,转换catching(t) either expr将导致Either[T, E]where T是throwable的类型,并且E是表达式的类型.然后可以通过a将其转换为特定值fold.
或者另一个版本:
val date =
handling(classOf[PE]) by (_ => new Date) apply parseDate
Run Code Online (Sandbox Code Playgroud)
这可能更清楚一点 - 以下是等价的:
handling(t) by g apply f
try { f } catch { case _ : t => g }
Run Code Online (Sandbox Code Playgroud)
这里有些例子:
编译/斯卡拉/工具/ NSC /解释/ InteractiveReader.scala
def readLine(prompt: String): String = {
def handler: Catcher[String] = {
case e: IOException if restartSystemCall(e) => readLine(prompt)
}
catching(handler) { readOneLine(prompt) }
}
Run Code Online (Sandbox Code Playgroud)
编译/斯卡拉/工具/ 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
}
}
Run Code Online (Sandbox Code Playgroud)
编译/斯卡拉/工具/ NSC/IO/Process.scala
def exitValue(): Option[Int] =
catching(classOf[IllegalThreadStateException]) opt process.exitValue()
Run Code Online (Sandbox Code Playgroud)
库/斯卡拉/ XML /包括/萨克斯/ Main.scala
def saxe[T](body: => T) = catching[T](classOf[SAXException]) opt body
...
ignoring(classOf[SAXException]) {
includer.setProperty(lexicalHandler, s)
s setFilter includer
}
Run Code Online (Sandbox Code Playgroud)