Suppose you want to execute your code regardless of an exception being thrown or not, then you should use the finally clause. You can place it inside the try block as follows. Here is an example:
try {
val f = new FileReader("data/data.txt")
} catch {
case ex: FileNotFoundException => println("File not found exception")
} finally { println("Dude! this code always executes") }
}
Now, here's the complete example of using try...catch...finally:
package com.chapter3.ScalaFP
import java.io.IOException
import java.io.FileReader
import java.io.FileNotFoundException
object TryCatch {
def main(args: Array[String]) {
try {
val f = new FileReader("data/data.txt")
} catch {
case ex: FileNotFoundException => println("File not found
exception")
case ex: IOException => println("IO Exception")
} finally {
println("Finally block always executes!")
}
}
}
The output of the preceding code is as follows:
File not found exception
Finally block always executes!
Next, we will discuss another powerful feature in Scala called Either.