3.16. Matching One or More Exceptions with try/catch
Problem
You want to catch one or more exceptions in a
try/catch block.
Solution
The Scala
try/catch/finally
syntax is similar to Java, but it uses the match expression approach in
the catch block:
vals="Foo"try{vali=s.toInt}catch{casee:Exception=>e.printStackTrace}
When you need to catch and handle multiple exceptions, just add
the exception types as different case
statements:
try{openAndReadAFile(filename)}catch{casee:FileNotFoundException=>println("Couldn't find that file.")casee:IOException=>println("Had an IOException trying to read that file")}
Discussion
As shown, the Scala match expression syntax is used to match different possible exceptions. If you’re not concerned about which specific exceptions might be thrown, and want to catch them all and do something with them (such as log them), use this syntax:
try{openAndReadAFile("foo")}catch{caset:Throwable=>t.printStackTrace()}
You can also catch them all and ignore them like this:
try{vali=s.toInt}catch{case_:Throwable=>println("exception ignored")}
As with Java, you can throw an exception from a catch clause, but because Scala doesn’t have
checked exceptions, you don’t need to specify that a method throws the
exception. This is demonstrated in the following example, where the
method isn’t annotated in any way:
// nothing required heredeftoInt(s:String):Option[Int]=try{Some(s.toInt)}catch{casee:Exception=>throw ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access