3
這裏下面是如何處理意外的錯誤一個簡單的例子:是否有可能跳轉到一個嵌套的外部「case」語句?
try {
// some code that may throw an exception...
} catch {
case e: MyException => e.errorCode match {
case Some(ErrorCodes.ERROR_ONE) => println("error 1")
case Some(ErrorCodes.ERROR_TWO) => println("error 2")
case _ => println("unhandled error")
}
case _ => println("unhandled error")
}
正如你可以在上面的代碼中看到,無論是頂級case
對異常和錯誤代碼嵌套case
結束一種類捕獲全部來處理意外錯誤。該代碼的作品...但我想知道是否有一個更優雅的方式,讓我避免重複,只有一個捕獲所有語句[即println("unhandled error")
]:
try {
// some code that may throw an exception...
} catch {
case e: MyException => e.errorCode match {
case Some(ErrorCodes.ERROR_ONE) => println("error 1")
case Some(ErrorCodes.ERROR_TWO) => println("error 2")
// case _ => println("unhandled error")
// is it possible to jump to the outer *catch all* statement?
}
case _ => println("unhandled error")
}
謝謝。
我不認爲那裏是打破案例陳述的直接方式。但是,也許你可以讓你的'MyException'成爲一個案例類和模式匹配呢?或者,爲它寫一個提取器? –