Theoretical Paper
- Computer Organization
- Data Structure
- Digital Electronics
- Object Oriented Programming
- Discrete Mathematics
- Graph Theory
- Operating Systems
- Software Engineering
- Computer Graphics
- Database Management System
- Operation Research
- Computer Networking
- Image Processing
- Internet Technologies
- Micro Processor
- E-Commerce & ERP
- Dart Programming
- Flutter Tutorial
- Numerical Methods Tutorials
- Flutter Tutorials
- Kotlin Tutorial
Practical Paper
Industrial Training
Nested Try Block
We can also able to use nested try block whenever required. Nested try catch block is such block in which one try catch block is implemented into another try block.
The requirement of nested try catch block is arises when a block of code generates an exception and within that block another code statements also generates another exception.
Syntax of nested try block
.. try { // code block try { // code block } catch(e: SomeException) { } } catch(e: SomeException) { } .. .. try { // code block try { // code block } catch(e: SomeException) { } } catch(e: SomeException) { } ..
Kotlin nested try block example
fun main(args: Array< String>) { val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512) val deno = intArrayOf(2, 0, 4, 4, 0, 8) try { for (i in nume.indices) { try { println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i]) } catch (exc: ArithmeticException) { println("Can't divided by Zero!") } } } catch (exc: ArrayIndexOutOfBoundsException) { println("Element not found.") } } fun main(args: Array< String>) { val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512) val deno = intArrayOf(2, 0, 4, 4, 0, 8) try { for (i in nume.indices) { try { println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i]) } catch (exc: ArithmeticException) { println("Can't divided by Zero!") } } } catch (exc: ArrayIndexOutOfBoundsException) { println("Element not found.") } }
Output:
4 / 2 is 2 Can't divided by Zero! 16 / 4 is 4 32 / 4 is 8 Can't divided by Zero! 128 / 8 is 16 Element not found.