Catching multiple exceptions at once in Scala

Viewed 30388
5 Answers

Scala version 3 (released in 2021) supports union types, which creates another solution to the already mentioned solutions, although it looks very very similar, but it's different:

(For comparison, I've used the code from solution https://stackoverflow.com/a/6385333/1039774 from 2011, and changed it to Scala 3 with union types, and the new operator can be omitted in Scala 3.)

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