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.



Hi I am Pluto.