Updated April 12, 2023
Introduction to Scala Try Catch
In programming languages try catch is used to handle exception in code. Exception is an unexpected event which occurs while the execution of the program and the program will terminate unexpectedly without the completion of whole lines of code present in the program. So to handle this event we use try catch block to process our flow of program normally. Exception leads to an abnormal flow of the program. So by using try and catch we handle this event and promote normal flow.
Syntax:
try {
// suspected code goes here
}catch {
// to catch exception. We can write multiple case statements here. That is a series of case / /statement.
}
In the above syntax, we write our suspected code that can lead to any exception inside the try block and the catch statement is responsible to handle our exception if occur.
So any sensitive part of code that can lead to an exception which can place inside try block and surrounded by a catch block. Always remember try blocks always followed by catch block.
How Try Catch Block Work in Scala?
In scala try catch blocks different from the java try catch block. The difference is in Scala is we need to provide a series of exceptions inside a single catch block in the form of a case statement, but in java, we can have multiple catch blocks.
- Try Block: In Scala inside try lock we write our risky code that can throw an exception.
- Catch Block: In Scala, catch block is a series of exception statements in the form of a case statement. The catch block is responsible to handle the exception. Both try and catch block provide us the normal execution of the program.
Let say we have;
- Start
- line 1 ..
- lin2 2 ..
- line 3 ..
- lien 5 .. some exception at this line
- line 6 ..
- line 7 ..
- end
In the above scenario what we have is 7 lines of code that we are trying to execute. But at line 5 we got one exception so without try and catch block the program will terminate at line 5 only rest of the code will not be executed no matter what.
But we surround this line 5 code with try and catch the program will not going to terminate at line 5 rather the catch block will handle the exception and the rest of the code will execute and perform the desired operation. So this is the main benefit of using try catch block.
We can have one program for beginners to understand the normal implementation of try catch block with better understanding;
Without try catch what problem we are facing to execute and handle our program let see in below scenario:
Code:
object Main extends App{
//our code goes here
var number = 10;
var value = number/0;
println("rest of the code.")
}
Output:
Explanation: In this example, we are trying to divide a number by zero. But the Scala compile will throw an exception saying “/ by zero” it falls under the category of runtime exception. So the rest of the lines will not be executed in this case. Now we will check this with try catch block.
With try catch we can now execute our whole program normally without facing any issues:
Code:
object Main extends App{
//cod
var number = 10;
try
{
var value = number/0;
}
catch
{
//case statements goes here (single or multiple)
case a: ArithmeticException =>
{
println("ArithmeticException : number is not divisiable by 0." )
}
}
println("rest of the code.")
}
Output:
In this example, we have surrounded our code by try catch so the rest of the program is working fine as expected. This is how it works in Scala.
Examples to Implement Scala Try Catch
Below are the examples of Scala Try Catch:
Example #1
In this example, we are trying to create one file and read from that file. If the file is not present it will throw us FileNotFoundException, if found then the program will work as expected.
Code:
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Main extends App{
try
{
//risky code
val t = new FileReader("sample.txt")
}
catch
{
case x: FileNotFoundException =>
{
//will print if exception occur.
println("FileNotFoundException: cannot find file specified.")
}
}
}
Output:
Example #2
In this example, we are using multiple case statements to handle our exception. We are handling arithmetic and file not found. Whichever the exception occurs first it will execute that catch statement and the rest of the program will execute normally.
Code:
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Main extends App{
// your code
try
{
//risky code goes here
val value = 10/0;
val t = new FileReader("sample.txt")
}
catch
{
case x: FileNotFoundException =>
{
//will print if exception occure.
println("FileNotFoundException: cananot find file sepcified.")
}
case x: ArithmeticException =>
{
// Displays this if the file is
// missing
println("ArithmeticException : cannot divide by zero exception.")
}
}
}
Output:
Example #3
In this example we are not specifying the exact exception rather we handle it by using ‘Throwable’. so if we do not want to specify the exact exception we can surround those exceptions using throwable. In can handle all types of exception in Scala. Here we are trying to reinitialize the array so it will give us ArrayIndexOutOfBoundsException as it reaches the length of the array.
Code:
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
import java.lang.Throwable
object Main extends App{
try{
varinitilizingArr = Array(500, 300, 200, 800, 1000, 30, 50)
initilizingArr(90)
}
//catch
catch{
//statement 1
case e: Throwable =>println("Throwable :: we have found one unknown exception : :"+ e)
}
println("rest of the code.")
}
Output:
Conclusion
So we should always surround our suspected or risky code with try and catch in order to continue the normal flow of the program. If we do not surround or do not use try catch our whole program will not be executed that will lead to some serious problem. try block is always followed by the catch block to handle the exception.
Recommended Articles
This is a guide to Scala Try Catch. Here we discuss a brief overview of Scala Try Catch and its different examples along with code Implementation. You can also go through our other suggested articles to learn more –