Return the same value for several exceptions

advertisements

Given a block that catches more than one exception is it possible to handle multiple exceptions without putting the desired value in every case block? e.g. it would be nice if something like this worked:

val foo: Int = try {
  //do stuff that results in an Int
} catch {
  case e: SomeException => //do something if this gets thrown
  case e: SomeOtherException => //do something different if this gets thrown
  0
}

But that results in a compile error (type mismatch; found : Unit required: Int). I could put the default in each throwable case e: SomeException => {/*do something if this gets thrown*/; 0} - but that just seems like code smell so I'm hoping there is a more elegant solution.


You could simply wrap the exception handling:

val foo: Int = try {
  //do stuff that results in an Int
  17
} catch { case t: Throwable => t match {
    case e: SomeException => //do something if this gets thrown
    case e: SomeOtherException => //do something different if this gets thrown
  }
  42
}