Search code examples
scalascala-2.8

Using scala.util.control.Exception


Does anybody have good examples of using scala.util.control.Exception version 2.12.0 (version 2.8.0), ? I am struggling to figure it out from the types.


Solution

  • Indeed - I also find it pretty confusing! Here's a problem where I have some property which may be a parseable date:

    def parse(s: String) : Date = new SimpleDateFormat("yyyy-MM-dd").parse(s)
    def parseDate = parse(System.getProperty("foo.bar"))
    
    type PE = ParseException
    import scala.util.control.Exception._
    
    val d1 = try { 
                 parseDate
               } catch { 
                 case e: PE => new Date
               }
    

    Switching this to a functional form:

    val date =
         catching(classOf[PE]) either parseDate fold (_ => new Date, identity(_) ) 
    

    In the above code, turns catching(t) either expr will result in an Either[T, E] where T is the throwable's type and E is the expression's type. This can then be converted to a specific value via a fold.

    Or another version again:

    val date =
         handling(classOf[PE]) by (_ => new Date) apply parseDate
    

    This is perhaps a little clearer - the following are equivalent:

    handling(t) by g apply f 
    try { f } catch { case _ : t => g }