Home »
Kotlin »
Kotlin Programs
Kotlin program of using finally block with try-catch block
Kotlin example to demonstrate the use finally block with try-catch block.
Submitted by IncludeHelp, on April 11, 2022
The finally with try-catch block
The finally block is always executed whether an exception is handled or not by the catch block. Here, we will use finally block with try and catch block.
Example 1:
// Importing the ArithmeticException class
import kotlin.ArithmeticException
fun main(args : Array<String>){
var x = 10
var y = 3
try{
println("10/3: " + x/y)
x = 10
y = 0
println("10/0: " + x/y)
}
catch(e: ArithmeticException){
// caught and handles it
println("Divide by zero exception")
}
finally{
// Finally block
println("The finally block.")
}
}
Output:
10/3: 3
Divide by zero exception
The finally block.
Example 2:
fun main(args : Array<String>){
try{
var intarray = arrayOf(10, 20, 30, 40, 50, 60)
// Prints the value
println("intarray[5]: " + intarray[5])
// Generates an exception
println("intarray[6]: " + intarray[6])
}
catch(e: IndexOutOfBoundsException){
// caught and handles it
println("Exception: " + e)
}
finally {
println("Finally block.")
}
}
Output:
intarray[5]: 60
Exception: java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
Finally block.
Kotlin Exception Handling Programs »