ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.