How to match one or more exceptions with try/catch in Scala

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
    }

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.