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.
- Exception raised: Control flow will be finally block followed by default exception handling mechanism If exception has been occurred in try block .
Example:
object GFG
{
def main(args : Array[String])
{
var arr = new Array[Int]( 4 )
try
{
var i = arr( 4 )
println( "Inside try block" )
}
finally
{
println( "finally block executed" )
}
println( "Outside try-finally clause" )
}
}
|
Output:
finally block executed
- Exception not raised: Control flow will be finally block followed by rest of the program if exception is not occurred in try block.
Example:
object GFG
{
def main(args : Array[String])
{
try
{
val str 1 = "123" .toInt
println( "Inside try block" )
}
finally
{
println( "finally block 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 :
object GFG
{
def main(args : Array[String])
{
try
{
var array = Array( 4 , 2 , 7 )
var b = array( 5 )
}
catch
{
case e : ArithmeticException => println(e)
case ex : Exception => println(ex)
case th : Throwable => println( "unknown exception" +th)
}
finally
{
println( "this block always executes" )
}
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.