Exception Handling in Scala
A Exception Handling in Scala is same as Java Exception Handling. In scala method can be terminated instead of returning by throwing an exception.
![PHP Try Catch Example: Exception & Error Handling Tutorial](https://www.guru99.com/images/2013/04/exception_flowchart.png)
![Scala Tutorials Part #24 - Exception Handling | Madusudanan](https://madusudanan.com/images/exceptions.png)
Use case 1 : try and catch
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object exceptioncatching {
def main(args: Array[String]) {
try {
val f = new FileReader(“input.txt”)
} catch {
case ex: FileNotFoundException =>{
println(“Missing file exception”)
}
case ex: IOException => {
println(“IO Exception”)
}
}
}
![](https://prwatech.in/blog/wp-content/uploads/2021/04/image.png)
Use case 2 : finally
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object finalexception {
//main function
def main(args: Array[String]) {
try {
val f = new FileReader(“Read.txt”)
} catch {
case ex: FileNotFoundException => {
println(“Missing file exception”)
}
case ex: IOException => {
println(“IO Exception”)
}
} finally {
println(“Exiting finally…”)
}
}
![](https://prwatech.in/blog/wp-content/uploads/2021/04/image-1.png)
use case 3: Throw
object throwobj {
def validate(article:Int)=
{
// Using throw keyword
if(article < 20)
throw new ArithmeticException(“You are not eligible for internship”)
else println(“You are eligible “)
}
// Main method
def main(args: Array[String])
{
validate(22)
}
}
![](https://prwatech.in/blog/wp-content/uploads/2021/04/image-68.png)