Left Index

Kotlin Finally Block

Finally block is such a block which execute every time either any Exception occur or not. It used with try block and can use without catch block.

Syntax:
try {
	// you code
} finally {
	// perform some action which is required
}

Syntax with catch block:
try {
	// you code
} catch(e: Exception) {
	// handle exception
} finally {
	// perform some action which is required
}

Example:
package com.theitbulls.kotlinex

import java.lang.ArithmeticException

fun main(args: Array<String>) {
	try {
		var num = 120 / 3
		println("Result: ${num}")
	} catch (e: Exception) {
		// handle exception
	} finally {
		println("This is finally block execute everytime")
	}
}
Output:
Result: 40
This is finally block execute everytime