Kotlin巢狀try-catch塊


還可以在需要時使用巢狀的try塊。 巢狀的try catch塊就是這樣一個塊:其中一個try catch塊在另一個try塊中實現。

當一個程式碼塊捕捉異常並且在該塊內另一個程式碼語句也需要捕捉另一個異常時,就會有巢狀的try catch塊的需要。

巢狀try塊的語法

..   
try    
{    
    // code block   
    try    
    {    
        // code block   
    }    
    catch(e: SomeException)    
    {    
    }    
}    
catch(e: SomeException)    
{    
}    
..

Kotlin巢狀try塊範例

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.")  
    }  
}

執行上面範例程式碼,得到以下結果 -

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.