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

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<br>
object Intellipaat {<br>
def main(args: Array[String]) {<br>
val file = new FileReader("intellipaat.txt")<br>
try {<br>
// Use the file<br>
} finally {<br>
file.close() // Be sure to close the file<br>
println(“File is closed”)<br>
}<br>
}<br>
}<br>

Output
File is closed

Our Big Data Courses Duration and Fees

Program Name
Start Date
Fees
Cohort Starts on: 19th Apr 2025
₹22,743
Cohort Starts on: 26th Apr 2025
₹22,743
Cohort Starts on: 19th Apr 2025
₹22,743

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.