Page Contents
What is an Exception ?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn’t actually have checked exceptions.
When you want to handle exceptions, you use a try-catch block like in Java except that the catch block uses matching to identify and handle the exceptions.
How to throw an exception in Scala ?
Same as in Java programming language. You create an exception object and then you throw it with the throw keyword as follows.
throw new IllegalArgumentException
How to catch exception in Scala ?
Scala allows you to try-catch any exception in a single block and then perform pattern matching against it using case blocks.
Example
In below mentioned example, we are trying to read a file that does not exist. The program must throw FileNotFoundException.
import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object ExceptionDemo{ def main(args: Array[String]) { try { val file= new FileReader("readMe.info") } catch { case e: FileNotFoundException => { println("File Does not exist") } case e: IOException => { println("IO Exception") } } } }
Save the above program in ExceptionDemo.scala. Compile and run the above program as mentioned below –
scalac ExceptionDemo.scala scala ExceptionDemo
Output
File Does not exist
The finally Clause
You can wrap an expression with a finally clause if you want to cause some code to execute no matter how the expression terminates. Try the following program.
Example
import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object ExceptionDemo{ def main(args: Array[String]) { try { val file= new FileReader("readMe.info") } catch { case e: FileNotFoundException => { println("File Does not exist") } case e: IOException => { println("IO Exception") } }finally { println("Finally block") } } }
Save the above program in ExceptionDemo.scala. Compile and run the above program as mentioned below –
scalac ExceptionDemo.scala scala ExceptionDemo
Output
File Does not exist Finally block