2014-06-05 18 views
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") 
} 

謝謝。

+2

我不認爲那裏是打破案例陳述的直接方式。但是,也許你可以讓你的'MyException'成爲一個案例類和模式匹配呢?或者,爲它寫一個提取器? –

回答

5

對於只有少數情況下,那麼你可以使用case ... if ...語句來避免嵌套的比賽如下:

try { 
    errorThrowingCall() 
} catch { 
    case e: MyException if e.errorCode == Some(ErrorCodes.ERROR_ONE) => println("error 1") 
    case e: MyException if e.errorCode == Some(ErrorCodes.ERROR_TWO) => println("error 2") 
    case _ => println("unhandled error") 
} 

或者作爲@Carsten建議,只是把你的異常轉換的情況下類:

case class MyException(errorCode : Option[Int]) extends Exception 

並做它的模式匹配如下所示:

try { 
    errorThrowingCall() 
} catch { 
    case MyException(Some(ErrorCodes.ERROR_ONE)) => println("error 1") 
    case MyException(Some(ErrorCodes.ERROR_TWO)) => println("error 2") 
    case _ => println("unhandled error") 
} 
相關問題