Scala has a
finally construct that helps you handle the exceptions that can occur in your code, such as when you attempt to access a website and its down, or when you try to read a file that doesn’t exist. The basic idea is that you try to access some resource, and if it fails, you catch the resulting exception and deal with it.
For example, when you attempt to read a file you can run into two possible exceptions:
When you need to work with those exceptions, you’ll write code that looks like this:
// somewhere earlier in your code: var content = "" // then later in your code you try to read a file’s content // into that variable: try content = readFile(filename) catch case e: FileNotFoundException => System.err.println("Couldn't find that file.") case e: IOException => System.err.println("Had an IOException trying to read that file")
Notice that you write your normal “success path” code inside the
try block. You do whatever you want to do there, and then catch its potential exceptions in the
catch block. If everything works, your
content variable is updated with text from the file, but if it fails, you print those error statements.
If you’ve used Java, the concept is the same, but the
case syntax here is consistent with the
case syntax that’s used in
match expressions, which you’ll see later in this book. You can also use a
finally clause, which I’ll show next.
finally clause takes a little bit more work, and it will also help if we cover a few more topics before I address it. For those details, see the second
finally lesson, which you’ll find just after the lessons on functions.
The exercises for this lesson are available here.