Catching multiple exceptions at once in Scala

TN. picture TN. · Jun 17, 2011 · Viewed 25.4k times · Source

How to catch multiple exceptions at once in Scala? Is there a better way than in C#: Catch multiple exceptions at once?

Answer

agilesteel picture agilesteel · Jun 17, 2011

You can bind the whole pattern to a variable like this:

try {
   throw new java.io.IOException("no such file")
} catch {
   // prints out "java.io.IOException: no such file"
   case e @ (_ : RuntimeException | _ : java.io.IOException) => println(e)
}

See the Scala Language Specification page 118 paragraph 8.1.11 called Pattern alternatives.

Watch Pattern Matching Unleashed for a deeper dive into pattern matching in Scala.