Try, Catch, Finally in Scala

Reading Time: 3 minutes

Overview

In this blog post we will look at exception handling in Scala. More preciesly try, catch and finally keyword in Scala, we will cover how it works, what are its used. In case you are new to programming check out this page to get started. One need to have very basic understanding about Scala syntax to follow along this blog. So, spin up your IDE and let’s get started.

Exceptions

Let’s first understand what are exception, because this is the reason we use these blocks. Exception in simple words are unwanted and unexpected events. These will occur at the time of execution of a program i.e. at Run Time. Situations that are not too dangerous so they are handled by the program itself.

All exceptions and errors are the sub-classes of the class Throwable, which is also the base class of the hierarchy try to understand this better with this flowchart.

Syntax : throw new ArithmeticException

The try/catch construct

If you are familiar with try and catch here is the thing, try catch construct in Scala is different from Java and other languages. It is an expression in Scala, Instead of writing catch blocks again and again for different scenarios try gives a value here which can be matched with cases present in catch block. As a result we do not have to write catch block for each and every possible exception. Awesome isn’t it ?

Completely new to the try/catch construct, try think of a piece of code that could throw an “Arithmetic Exception” exception. Now this code can can be handled using these two keywords try and catch, the syntax how this is written is referred to as try/catch construct.

import java.io.IOException
  
// Creating an object
object ExceptionalObject
{  
    // Main method
    def main(args:Array[String])
    {  
        try
        {
            /* 
              
             Now this line will not throw a compilation error because it is syntactically okay 
             but not logically correct    
           
            */ 
            var N = 5/0
               
        } 
        // after the exception is thrown by the try block it can be now handled in catch
        catch 
        {
            // Catch block contain cases and whatever case have the same exception that is thrown will get execute. 
            case i: IOException => 
            {
                println("IOException occurred.")
            }
            // In this case this case will run because 5/0 is an arithmetically wrong statement
            case a : ArithmeticException => 
            {
                println("Arithmetic Exception occurred.")
            }
   
        }
   
    }  
}  

Finally let’s talk about, “Finally”!

Scala finally block is used to execute the code that needs to get executed no matter the exception is thrown or not. This comes in very handy and useful. Wondering how? Finally can be used when we need to free up certain resources, closing connections etc. basically the codes that will be executed irrespective of the scenario.

try {
       //your scala code here
    } 
finally {
           println("this block of code is always executed")
           // your scala code here, such as to close a database connection
        }

In the above example you can see we haven’t added the catch block, because it is not always necessary to add a catch block. The above expression is syntactically correct and will work fine.

The “try-catch-finally” clause

The try-catch-finally will make sure that the code in finally will get executed even if the exception is thrown or not. Let’s see this with an example. In the example below we will throw the same exception (“Arithmetic Exception”) and will use finally to execute something.

// Creating object
object GFG
{ 
    // Main method
    def main(args:Array[String])
    { 
        try
        { 
            // creating an exception to throw
            val = 5/0
        }
        catch
        { 
            // Catch block contain cases.
            case e: ArithmeticException => println(e) // exception will be matched and handled here 
            case ex: Exception => println(ex) 
            case th: Throwable=> println("unknown exception"+th) 
        } 
        finally
        { 
            // Finally block will executeno matter what  
            println("this block always executes") 
        } 
          
        // rest program will execute 
        println(" rest of code executing") 
    } 
} 

Finally block will be executed.

To know more about exception handling in Scala refer to the docs.

Conclusion

In this blog we have seen how to use try/catch-construct and how to use try-catch-finally. We have discussed about the scenarios where we can use what we have learnt from this blog. Thanks for reading this blog. Check out our website knoldus.com for engineering solutions and you can find more awesome blogs at https://blog.knoldus.com.

1 thought on “Try, Catch, Finally in Scala

Comments are closed.