home search about rss feed twitter ko-fi

try/catch/finally (Scala 3 Video)

The try/catch/finally construct is used to catch and handle exceptions. The syntax is similar to other languages, like Java, but the syntax is consistent with match expressions.

General syntax:

try
    // some code that can throw 1+ exception types
catch
    // catch and handle the exceptions
    case e1: ExceptionType1 =>
        e1...
    case e2: ExceptionType2 =>
        e2...
finally
    // clean up your resources, i.e., call `.close`

Because it’s an expression, it can be used as the body of a function:

def makeInt(s: String): Int =
    try
        s.toInt
    catch
        case e: NumberFormatException => 0
    finally
        // close your resources
        println("finally!")

An OOP example looks like this:

import java.io.*

val filename = "/etc/passwd"
var stream: Stream[String] = null

try
    stream = Files.lines(Paths.get(filename))
catch
    // catch and handle the exceptions
    case ioe: IOException =>
        ioe.printStackTrace
    case fnf: FileNotFoundException =>
        fnf.printStackTrace
finally
    if stream != null then stream.close

Update: All of my new videos are now on
LearnScala.dev