Kotlin Nested try catch Block Tutorial With Example

In this tutorial, we will learn about how to use kotlin nested try catch block? why do we need it? etc.
In kotlin nested try catch block, we implement one try catch block inside another try catch block.

Syntax of nested try catch block in kotlin

    try {
        // write code that may generate error.

        // start of another try catch block
        try { // nested try catch block
            //write code that may generate error
        } catch (e: Exception1) {
            // write to handle exception
        }
        // end of another try catch block

    } catch (e: Exception2) {
        //write code to handle exception
    }

Example of kotlin nested try catch block

Example 1,

fun main(args: Array<String>) {
    val arr1 = intArrayOf(2, 4, 6, 8)
    try {
        for (index in arr1.indices) {
            try {
                println(arr1[index + 1])
            } catch (exc: ArithmeticException) {
                println("Number can't be divided by Zero!")
            }

        }
    } catch (exc: Exception) {
        println("Exception occurred: Exception")
    }
}

When you run the program, output will be –
4
6
8
Exception occurred: Exception

Note that we are printing next element of array in each iteration. So, at last iteration it will try to access next element in the array that does not exist.
Hence, it will through exception.

Exercises on Kotlin Nested try catch block

1. Guess the output of below program –

fun main(args: Array<String>) {
    val arr1 = intArrayOf(2, 4, 6, 8, 10, 12, 14)
    val arr2 = intArrayOf(2, 0, 3, 3, 0, 4)
    try {
        for (index in arr1.indices) {
            try {
                println(arr1[index].toString() + " / " + arr2[index] + " is " + arr1[index] / arr2[index])
            } catch (exc: ArithmeticException) {
                println("Number can't be divided by Zero!")
            }

        }
    } catch (exc: ArrayIndexOutOfBoundsException) {
        println("Exception occurred: ArrayIndexOutOfBoundsException")
    }
}

Leave a Reply