1

I would like to know the guarantees of the following pattern:

try {
  //business logic here
} catch {
  case t: Throwable =>
    //try to signal the error
    //shutdown the app
}

I'm interested in catching all unexpected exceptions (that can be thrown by any framework, library, custom code etc...), trying to record the error and shutting down the virtual machine.

In Scala what are the guarantees of the catch Throwable exception? Are there any differences with the java Exception hierarchy to take in consideration?

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Dario Balinzo
  • 671
  • 5
  • 8

2 Answers2

4

Throwable is defined in the JVM spec:

An exception in the Java Virtual Machine is represented by an instance of the class Throwable or one of its subclasses.

which means that both Scala and Java share the same definition of Throwable. In fact, scala.Throwable is just an alias for java.lang.Throwable. So in Scala, a catch clause that handles Throwable will catch all exceptions (and errors) thrown by the enclosed code, just like in Java.

There are any difference with the java Exception hierarchy to take in consideration?

Since Scala uses the same Throwable as Java, Exception and Errors represent the same things. The only "difference" (that I know of) is that in Scala, exceptions are sometimes used under the hood for flow control, so that if you want to catch non-fatal exceptions (thus excluding Errors), you should rather use catch NonFatal(e) instead of catch e : Exception. But this doesn't apply to catching Throwable directly

oowekyala
  • 7,518
  • 1
  • 15
  • 20
1

All harmless Throwables can be caught by:

  try {
    // dangerous
  } catch {
    case NonFatal(e) => log.error(e, "Something not that bad.")
  }

This way, you never catch an exception that a reasonable application should not try to catch.

OBarros
  • 132
  • 1
  • 9