Scala | Try-Catch Exceptions
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 :
// Scala program of try-catch
// exception
// Creating object
object
Arithmetic
{
// Main method
def
main(args
:
Array[String])
{
// Try clause
try
{
// Dividing a number
val
result
=
11
/
0
}
// Catch clause
catch
{
// Case statement
case
x
:
ArithmeticException
=>
{
// Display this if exception is found
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 :
// Scala program of Try-Catch
// Exception
import
java.io.FileReader
import
java.io.FileNotFoundException
import
java.io.IOException
// Creating object
object
GfG
{
// Main method
def
main(args
:
Array[String])
{
// Try clause
try
{
// Creating object for FileReader
val
t
=
new
FileReader(
"input.txt"
)
}
// Catch clause
catch
{
// Case statement-1
case
x
:
FileNotFoundException
=>
{
// Displays this if the file is
// missing
println(
"Exception: File missing"
)
}
// Case statement-2
case
x
:
IOException
=>
{
// Displays this if input/output
// exception is found
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.
Please Login to comment...