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

Scala FAQ: How do I handle exceptions in Scala?

Solution: Basic exception handling in Scala

Basic exception handling in Scala is handled with its try/catch/finally syntax.

For instance, 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.

NOTE: 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. Note that in this example I show the syntax to catch three different types of exceptions in the catch section:

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.

2024 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’s helpful. But if you’d like some more examples and details, read on...

A complete 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
    }
}

In this example I declare two var fields before the try/catch/finally block, and then use those fields inside the try section. If an exception is thrown in the try section, it’s caught in the catch section. Then in the finally section I make sure that I close my resources, being sure to check that they are defined before I call close on them.

If you’d like more details on that example, 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: