Scala: How to simply apply same method to all exceptions in catch block

Viewed 81

Consider following sample code

try{
    .....
}catch{
     case e1:Exception1 => { method1(..)}
     case e2:Exception2 => { method2(..)}
     case e3:Exception3 => { method3(..)}
}

Now if I'd like to run same method i.e. methodGeneral() to all exception (e1, e2, e3)

however how to avoid to apply the method in each block like below, but can achieve in one shot?

try{
    .....
}catch{
     case e1:Exception1 => { method1(..); methodGeneral();}
     case e2:Exception2 => { method2(..); methodGeneral();}
     case e3:Exception3 => { method3(..); methodGeneral();}
}
1 Answers

The Scala Try type offers a few more features than the basic try..catch. For example, you could do something like this.

import scala.util.Try

Try {
 . . .
}.recover{ excp:Throwable =>
  excp match {
     case e1:Exception1 => method1(..)
     case e2:Exception2 => method2(..)
     case e3:Exception3 => method3(..)
  }
  methodGeneral(excp)
}.get

This requires that the .recover code block returns the same type as the Try code block. If the return value is actually of no interest, such as Unit for example, then the .get can be omitted.


If you're really wedded to the old try..catch you might try something like this.

try {
  . . .
} catch {
  case excp: Throwable => 
    excp match {
      case e1:Exception1 => method1(..)
      case e2:Exception2 => method2(..)
      case e3:Exception3 => method3(..)
    }
    methodGeneral(excp)
}

It's still a good idea to ensure that the try block and catch block are type-compatible.

Related