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.
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
Example:
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer