• Articles
  • Tutorials
  • Interview Questions

Exception Handling in Scala - Everything You Need to Know

Exception handling in Scala

Exceptions are 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.

Become a Big Data Architect

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.

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.

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

Course Schedule

Name Date Details
Big Data Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Big Data Engineering

Abhijit is a Technical Research Analyst specialising in Big Data and Azure Data Engineering. He has 4+ years of experience in the Big data domain and provides consultancy services to several Fortune 500 companies. His expertise includes breaking down highly technical concepts into easy-to-understand content.