Kotlin finally Block Tutorial With Example

In this kotlin tutorial, we will learn about kotlin finally block in exception. We will learn why should we use it? how is finally block used in exception? etc.

Kotlin finally block is used to perform actions that we must do irrespective of whether exception is handled or not. So, you must use it with caution.

Syntax of kotlin finally block with try catch block
try {
   // Write code that may generate exception
} catch (e: Exception) {
    // Write code to handle exception
} finally {
    // Write code to perform actions that you must do whether exception occurs or not.
}

– You can also use finally block with try block without using catch block in kotlin.

Syntax of kotlin finally block with try block in exception
try {
   // Write code that may generate exception
} finally {
    // Write code to perform actions that you must do whether exception occurs or not.
}

Examples of kotlin finally block with try catch

1. Run below program

fun main(args: Array<String>) {
    val arr = intArrayOf(1, 2, 3, 4, 5, 6)
    try {
        println(arr[6])
    } catch (e: ArrayIndexOutOfBoundsException) {
        println("Exception occurred: ArrayIndexOutOfBoundsException")
    } finally {
        println("Program exiting...")
    }
}

When you run the program, you will get below output –
Exception occurred: ArrayIndexOutOfBoundsException
Program exiting…

Note that finally block is executed after handling exception i.e. after executing catch block.

2. Run below program,

fun main(args: Array<String>) {
    val arr = intArrayOf(1, 2, 3, 4, 5, 6)
    try {
        println(arr[6])
    } finally {
        println("Program exiting...")
    }
}

When you run the above program, you will get output –
Program exiting…
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 6

Note that we have not handled exception in this program. So, finally block is executed after try block.

Exercises on finally block with try catch block in kotlin

1. Guess the output of below program.

fun main(args: Array<String>) {
    val arr = intArrayOf(1, 2, 3, 4, 5, 6)
    try {
        println(arr[6])
    } finally {
        println(arr[6])
        println("Program exiting...")
    }
}

2. Guess the output of below program.

fun main(args: Array<String>) {
    val arr = intArrayOf(1, 2, 3, 4, 5, 6)
    try {
        println(arr[6])
    } finally {
        println("Program exiting...")
        println(arr[6])
    }
}

3. Guess the output of below program

fun main(args: Array<String>) {
    val numb: Int? = null
    try {
        println(numb.toString())
    } catch (e: NullPointerException) {
        println("Exception occurred: NullPointerException")
    } finally {
        println("Program exiting...")
    }
}

Leave a Reply