Q:

Kotlin program of using finally block with try-catch block

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now