Search code examples
scalaexceptionpattern-matchingtry-catch

Catching multiple exceptions at once in Scala


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


Solution

  • 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.