Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 464
TN. Avatar asked Jun 17 '11 09:06

TN.


People also ask

How can I get 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.

Can we catch multiple exceptions in the catch block?

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.

Can we handle multiple exceptions by using single catch block?

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.

How do you catch exceptions in Scala?

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.


1 Answers

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.

like image 115
agilesteel Avatar answered Sep 19 '22 13:09

agilesteel