If You are interested to learn about the Scala Field Overriding
Scala provides try and catch block to handle exception. The try block is used to enclose suspect code. The catch block is used to handle exception occurred in try block. You can have any number of try catch block in your program according to need. 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. }
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.

Scala Try Catch Example
In the following program, we have enclosed our suspect code inside try block. After try block we have used a catch handler to catch exception. If any exception occurs, catch handler will handle it and program will not terminate abnormally.
class Exception Example{ def divide(a:Int, b:Int) = { try{ a/b }catch{ case : Arithmetic Exception => println(e) } println("Rest of the code is executing...") } } object Main Object{ def main(args:Array[String]){ var e = new Exception Example() e.divide(100,0) } }
Output:
java.lang.Arithmetic Exception: / by zero
Rest of the code is executing...
Scala Try Catch Example 2
In this example, we have two cases in our catch handler. First case will handle only arithmetic type exception. Second case has Throwable class which is a super class in exception hierarchy. The second case is able to handle any type of exception in your program. Sometimes when you don’t know about the type of exception, you can use super class.Play Video
class Exception Example{ def divide(a:Int, b:Int) = { try{ a/b var arr = Array(1,2) arr(10) }catch{ case e: ArithmeticException => println(e) case ex: Throwable =>println("found a unknown exception"+ ex) } println("Rest of the code is executing...") } } object Main Object{ def main(args:Array[String]){ var e = new Exception Example() e.divide(100,10) } }
Output:
found a unknown exception java.lang.Array Index Out Of Bounds Exception: 10
Rest of the code is executing...