Kotlin program to demonstrate the nested try block

Kotlin example to demonstrate the nested try block.
Submitted by IncludeHelp, on April 12, 2022

The nested try-catch block is required when an exception occurs in the inner try-catch block and it is not handled by the inner catch blocks. In that case, the outer try-catch blocks will be used for handling that exception.

Syntax:

// Outer try block
try {
  // Inner try block   
  try {
    // Code section
  } catch (e: SomeException) {
    // Code to handle exception
  }
} catch (e: SomeException) {
  // Code to handle exception
}

Example:

fun main(args: Array < String > ) {
  // Integer array 
  val arr = arrayOf(10, 20, 30, 40, 50)

  try {
    for (i in arr.indices) {
      try {
        // Generate a random number 
        var number = (0..4).random()
        // Divide the array elements by the 
        // generated random number 
        println(arr[i + 1] / number)

      } catch (exp: ArithmeticException) {
        // Catch and handle the exception
        println(exp.message)
      }
    }
  } catch (exp: ArrayIndexOutOfBoundsException) {
    // Catch and handle the exception
    println(exp.message)
  }
}

Output:

/ by zero
30
10
16
Index 5 out of bounds for length 5

Kotlin Exception Handling Programs »




Comments and Discussions!

Load comments ↻





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