Is it possible to jump to an outer "case" statement from a nested one?
scala
Solution
For only a few cases then you can use `case ... if ...` statement to avoid the nested match as following:
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")
}
Alternatively as @Carsten suggests, just turn your exception into the case class:
case class MyException(errorCode : Option[Int]) extends Exception
and do pattern matching on it as shown below:
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")
}
Problem
Here below is a simple example of how to handle unexpected errors: ``` 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") } ``` As you can see in the code above, both the top level `case` on the exceptions and the nested `case` on the error codes end in a kind of catch all to handle unexpected errors. The code works... but I'm wondering whether there is a more elegant way that let me avoid the repetition and have just one catch all statement [i.e. `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") } ``` Thanks.