Exception handling in Scala

Exceptions are the events which can change the flow of control through a program. When you want to handle exceptions, you use a try{…}catch{…} block like you would in Java except that the catch block uses matching to identify and handle the exceptions.

 Throwing Exceptions
Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword:

throw new IllegalArgumentException
Catching Expressions

In a single block scala permits you to try and catch exception and then it performs pattern matching by the help of case blocks.
e.g.

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Intellipaat {
def main(args: Array[String]) {
try {
val i = new FileReader("intellipaat.txt")
} catch {
case ex: FileNotFoundException =>{
println("File not found Exception")
}
case ex: IOException => {
println("Input /Output Exception")
}
}
}
}

Output
File not found Exception
The finally clause:
If you want to cause some code to execute no matter how the expression terminates then you can enclose an expression with a finally clause. For example you want to close the open file even if a method exists by throwing an exception.

e.g.

import java.io.FileReader
object Intellipaat {
def main(args: Array[String]) {
val file = new FileReader("intellipaat.txt")
try {
// Use the file
} finally {
file.close() // Be sure to close the file
println(“File is closed”)
}
}
}

Output
File is closed

Previous Next

Recommended Videos