Kotlin教程:嵌套trycatch块

2023年 7月 12日 23.5k 0

可以在需要时使用嵌套的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) {  
    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.")  
    }  
}

Kotlin

执行上面示例代码,得到以下结果 -

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.

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-nested-try-block.html#article-start

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论