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

Scala FAQ: How do I handle exceptions in Scala?

Solution: Basic exception handling in Scala is handled with its try/catch/finally syntax. (See the end of this article for links to tutorials on advanced exception handling in Scala.)

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.

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:


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 =; c != −1}) {
    } 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{FileNotFoundException, IOException}

val filename = "/etc/passwd"
try {
    for (line <- Source.fromFile(filename).getLines) {
} 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.


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: