Search code examples
scalawarningsexceptiontry-catchcatch-all

Catch all exceptions in Scala 2.8 RC1


I have the following dummy Scala code in the file test.scala:

class Transaction {
  def begin() {}
  def commit() {}
  def rollback() {}
}

object Test extends Application {
  def doSomething() {}

  val t = new Transaction()
  t.begin()
  try {
    doSomething()
    t.commit()
  } catch {
    case _ => t.rollback()
  }
}

If I compile this on Scala 2.8 RC1 with scalac -Xstrict-warnings test.scala I'll get the following warning:

test.scala:16: warning: catch clause swallows everything: not advised.
    case _ => t.rollback()
    ^
one warning found

So, if catch-all expressions are not advised, how am I supposed to implement such a pattern instead? And apart from that why are such expressions not advised anyhow?


Solution

  • The warning exists because you probably don't want to catch everything. For example, it's generally inadvisable to try to catch anything in java.lang.Error since it's often hard to recover from such things. (Chances are good that you'll be thrown out of your catch block with another exception.)

    Also, because you can't usefully catch everything, this isn't a safe way to implement atomic/failsafe transactions. You're better off with something like

    try {
      t.commit()
    } finally {
      if (!t.checkCommitted()) {
        t.rollback()
        if (!t.checkRolledback()) throw new FUBARed(t)
      }
    }
    

    with additional testing when reading in a new t to make sure it's in a sensible state.