Sunday, 25 December 2011

Alternative to try-catch in Scala

I just saw such a nice control abstraction in Scala, that I wanted to share it. The original idea comes from akka-samples, I just modified it slightly to be more generic.
connected {
doSomethingDangerous()
} otherwise {
println("Error! Got disconnected.")
}
def doSomethingDangerous() = {/*...*/}
def connected(body: => Unit): Result =
try {
body; Ok
} catch {
case e: ClosedChannelException => Failed
}
trait Result { def otherwise(onError: => Unit): Unit}
case object Ok extends Result { def otherwise(onError: => Unit) = () /* do nothing */}
case object Failed extends Result { def otherwise(onError: => Unit) = onError}
view raw gistfile1.scala hosted with ❤ by GitHub


In this example the otherwise block gets executed only if system throws ClosedChannelExeption, but I could easily imagine other control abstractions hiding different exception types.

No comments:

Post a Comment