How to catch multiple exceptions at once in Scala? Is there a better way than in C#: Catch multiple exceptions at once?
When catching multiple exceptions in a single catch block, the rule is generalized to specialized. This means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception only instead of catching multiple specialized exceptions.
Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
The try/catch construct is different in Scala than in Java, try/catch in Scala is an expression. The exception in Scala and that results in a value can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With