Open In App

Scala | Finally Exceptions

Improve
Improve
Like Article
Like
Save
Share
Report

Scala finally block is used to execute important code such as closing connection, stream or releasing resources( it can be file, network connection, database connection etc). It will be always executed not matter if an exception is thrown or not. The finally block will be executed after the try and catch blocks, but before control transfers back to its origin.
Syntax:

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
        }
Control flow in try-finally

In this case, no matter whether an exception occur in try-block or not, finally will always be executed. But control flow will depend on whether exception has occurred in try block or not.

  1. Exception raised: Control flow will be finally block followed by default exception handling mechanism If exception has been occurred in try block .
    Example:




    // Scala program to demonstrate 
    // control flow of try-finally clause 
    // when exception occur in try block 
      
    // Creating object
    object GFG 
        // Main method 
        def main(args: Array[String]) 
        
            var arr = new Array[Int](4
              
            try
            
                var i = arr(4
                  
                // this statement will never execute 
                // as exception is raised by above statement 
                println("Inside try block"
            
              
            finally
            
                println("finally block executed"
            
              
            // rest program will not execute 
            println("Outside try-finally clause"
          
        
    }

    
    

    Output:

    finally block executed
  2. Exception not raised: Control flow will be finally block followed by rest of the program if exception is not occurred in try block.
    Example:




    // Scala program to demonstrate  
    // control flow of try-finally clause 
    // when exception doesn't occur in try block 
      
    // Creating object
    object GFG 
        // Main method 
        def main(args: Array[String])  
        
               
          try
            
                val str1 = "123".toInt 
                  
                // this statement will execute 
                // as no any exception is raised 
               // by above statement 
                println("Inside try block"
            
                
            finally
            
                println("finally block executed"
            
                
            // rest program will be executed 
            println("Outside try-finally clause"
        
            
      
    }

    
    

    Output:

    Inside try block
    finally block executed
    Outside try-finally clause
try-catch-finally clause

The finally keyword is used in association with a try/catch block and guarantees that a section of code will be executed, even if an exception is thrown.
Example :




// Scala program of try-catch-finally clause 
  
// Creating object
object GFG
    // Main method
    def main(args:Array[String])
    
        try
        
            // create array
            var array = Array(4, 2, 7
            var b = array(5
        }
        catch
        
            // Catch block contain cases.
            case e: ArithmeticException => println(e) 
            case ex: Exception => println(ex) 
            case th: Throwable=> println("unknown exception"+th) 
        
        finally
        
            // Finally block will execute
            println("this block always executes"
        
          
        // rest program will execute 
        println(" rest of code executing"
    


Output

java.lang.ArrayIndexOutOfBoundsException: 5
this block always executes
Rest of code executing

In above example we create an array in try block and from that array assigning the value to variable b, but it throw an exception because the index of array we are using to assign the value to variable b i.e. out of range of array indexes. catch block catch that exception and print message and finally block always executes no matter what.



Last Updated : 29 Mar, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads