Catching exception using try and catch

Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. The basic syntax of using try...catch in Scala is as follows:

try
{
// your scala code should go 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 should go here, such as to close a database connection
}

Thus, if you throw an exception, then you need to use the try...catch block in order to handle it nicely without crashing with an internal exception message:

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")
}
}
}

If there's no file named data.txt, in the path/data under your project tree, you will experience FileNotFoundException as follows:

The output of the preceding code is as follows:

File not found exception

Now, let's have a brief example of using the finally clause in Scala to make the try...catch block complete.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.143.73