Scala exception handling (try/catch/finally and more)

Scala FAQ: How do I handle exceptions in Scala?

Basic exception handling

Solution: Basic exception handling in Scala is handled with its try/catch/finally syntax. If you’re writing a function, typically you want to catch exceptions with try/catch/finally and then return a functional error handling type like Option, Try, or Either. (See the end of this article for links to tutorials on advanced exception handling in Scala.)

Scala’s try/catch/finally syntax

Here’s an example of Scala’s try/catch/finally syntax:

try {
    // your scala code here
} 
catch {
    case foo: FooException => handleFooException(foo)
    case bar: BarException => handleBarException(bar)
    case _: Throwable => println("Got some other kind of exception")
}
finally {
    // your scala code here, such as to close a database connection
}

A great thing about the catch clause in particular is that it’s consistent with the Scala match expression syntax.

2021 Update: If you’re using Scala 3, you don’t need the curly braces shown in that example.

If all you needed was an example of Scala’s try/catch/finally syntax, I hope that is helpful. But if you’d like some examples and more details, read on...

A Scala try/catch/finally example

Here’s an example of exception handling in Scala when opening and copying a binary file:

import java.io._

object CopyBytes extends App {
    var in = None: Option[FileInputStream]
    var out = None: Option[FileOutputStream]
    try {
        in = Some(new FileInputStream("/tmp/Test.class"))
        out = Some(new FileOutputStream("/tmp/Test.class.copy"))
        var c = 0
        while ({c = in.get.read; c != −1}) {
            out.get.write(c)
        }
    } catch {
        case e: IOException => e.printStackTrace
    } finally {
        println("entered finally ...")
        if (in.isDefined) in.get.close
        if (out.isDefined) out.get.close
    }
}

If that code doesn’t make sense, I write more about it in my “How to declare a variable (var) before using it in try/catch/finally” tutorial.

A try/catch example

Before I go, here’s another example of how to use try/catch while trying to read a file in Scala. It uses a different approach to read a file than the previous example:

import scala.io.Source
import java.io.{FileNotFoundException, IOException}

val filename = "/etc/passwd"
try {
    for (line <- Source.fromFile(filename).getLines) {
        println(line)
    }
} catch {
    case e: FileNotFoundException => println("Couldn't find that file.")
    case e: IOException => println("Got an IOException!")
}

This example comes from my “How to open and read text files in Scala” tutorial.

Discussion

It’s important to note that in functional programming in Scala, you don’t allow exceptions to leave methods (functions). I write about this in my “Functional error handling in Scala” tutorial, and in my book, Functional Programming, Simplified.

More Scala exception handling information

See these tutorials for more information on exception handling in Scala:

As I mentioned, the Scala catch syntax is similar to the Scala match expression syntax. Here are some tutorials that demonstrate that syntax: