Q:

Kotlin program to demonstrate the nested try block

0

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
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now