How to catch multiple exceptions at once in Scala? Is there a better way than in C#: Catch multiple exceptions at once?
How to catch multiple exceptions at once in Scala? Is there a better way than in C#: Catch multiple exceptions at once?
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)
}