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.
// 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.
Example 1:
Output:
Example 2:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer