Functional try & catch with Scala

That might be one case where it is not desirable to go functional. The allready mentioned loan pattern is only an encapsulation of the imparative version of error handling, but that has nothing to do with functional programming, and also doenst take care of error handling.

If you really wanted it functional you could do it with an error handling monad. For good reasons the link I provide is Haskell specific documentation to this, as Scala is not supporting this kind of "hardcore" functional practice so well.

I would reccomend to you to go the imperative way and use try catch finally... you could also extend the loan pattern with error handling but that means you have to either write special functions if you want to treat errors differently in some situations or you would have to pass over an partial function for error handling (which is nothing else than what you allready got inside the catch block in your code).


The loan pattern is implemented in various ways in Josh Suereth's scala-arm library on github.

You can then use a resource like this:

val result = managed(new FileInputStream(in)).map(func(_)).opt 

which would return the result of func wrapped in an Option and take care of closing the input stream.

To deal with the possible exceptions when creating the resource, you can combine with the scala.util.control.Exception object:

import resource._
import util.control.Exception.allCatch

allCatch either { 
  managed(new FileInputStream(in)).map(func(_)).opt 
} match {
  case Left(exception) => println(exception)
  case Right(Some(result)) => println(result)
  case _ =>
}

Use the Loan pattern (dead link) non permanent link to new location.