This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.16, “How to match one or more exceptions with try/catch in Scala.”
Problem
You want to catch one or more exceptions in a Scala 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:
val s = "Foo" try { val i = s.toInt } catch { case e: 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 { case e: FileNotFoundException => println("Couldn't find that file.") case e: 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 { case t: Throwable => t.printStackTrace() }
You can also catch them all and ignore them like this:
try { val i = 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 here def toInt(s: String): Option[Int] = try { Some(s.toInt) } catch { case e: Exception => throw e }
If you prefer to declare the exceptions that your method throws, or you need to interact with Java, add the @throws
annotation to your method definition:
@throws(classOf[NumberFormatException]) def toInt(s: String): Option[Int] = try { Some(s.toInt) } catch { case e: NumberFormatException => throw e }
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
See Also
- Recipe 5.8, “Declaring That a Scala Method Can Throw an Exception” for more examples of declaring that a method can throw an exception
- Recipe 2.1, “Parsing a Number from a String” for more examples of a toInt method