scala.util.Try - chain to handle all success and error cases
scala.util.Try is pretty awesome and you should read Daniel’s introductory post if you don’t know it yet. I just ported some code from using exception handling to using Try: lines of code went down to a third, readability improved heavily.
If you need to handle all success and error cases you could chain Try … recover, but that get’s a bit clunky if you’ve got more than two Trys, because you have to indent it. Another option is to chain orElse:
def trySomething = Try { throw new Exception("didn't work"); -1 }
def trySomethingElse = Try { 42 }
trySomething orElse trySomethingElse map {
case 42 ⇒ //wow, it worked
case -1 ⇒ //no, this will never happen
} recover {
case e: Throwable ⇒ // in case both failed
}