Exception handling in Scala

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

Wish to get certified in Scala! Learn Scala from top Scala experts and excel in your career with Intellipaat’s Scala certification!

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 the exception and then it performs pattern matching with the help of case blocks.

Prepare yourself for the industry by going through this Top Apache Spark and Scala Interview Questions and Answers!
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 exits by throwing an exception.
Still, have queries? Come to Intellipaat’s Big Data Community, clarify all your doubts, and excel in your career!

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

Are you interested in learning Scala from experts? Enroll in our Scala training in Bangalore now!

Recommended Videos

Leave a Reply

Your email address will not be published. Required fields are marked *