Kotlin program of using finally block with try block

Kotlin example to demonstrate the use finally block with try block.
Submitted by IncludeHelp, on April 11, 2022

The finally with try block

The finally block is always executed whether an exception is handled or not by the catch block. The finally block is also used with the try block for skipping the 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)
	}
	finally{
		// Finally block
		println("The finally block.")
	}
}

Output:

10/3: 3
The finally block.
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at FileKt.main (File.kt:12) 
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2) 
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1) 

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])
	}
	finally {
		// Finally block
		println("Finally block.")
	}
}

Output:

intarray[5]: 60
Finally block.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
 at FileKt.main (File.kt:8) 
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (:-2) 
 at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (:-1) 
 

Kotlin Exception Handling Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.