The Try-Catch construct is different in Scala than in Java, Try-Catch in Scala is an expression. the Scala make use of pattern matching in the catch clause. Suppose, we have to implement a series of code which can throw an exception and if we want to control that exception then we should utilize the Try-Catch segment as it permits us to try-catch each and every type of exception in only one block, we need to write a series of case statements in catch as Scala uses matching in order to analyze and handle the exceptions.
-
Example :
object Arithmetic
{
def main(args : Array[String])
{
try
{
val result = 11 / 0
}
catch
{
case x : ArithmeticException =>
{
println( "Exception: A number is not divisible by zero." )
}
}
}
}
|
Output:
Exception: A number is not divisible by zero.
Here, an exception is thrown as a number is not divisible by zero.
-
Example :
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object GfG
{
def main(args : Array[String])
{
try
{
val t = new FileReader( "input.txt" )
}
catch
{
case x : FileNotFoundException =>
{
println( "Exception: File missing" )
}
case x : IOException =>
{
println( "Input/output Exception" )
}
}
}
}
|
Output:
Exception: File missing
Here, the try block is executed first and if any exception is thrown then each of the cases of the catch clause is checked and the one which matches the exception thrown is returned as output.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Apr, 2019
Like Article
Save Article