Kotlin教程:嵌套try-catch块

2020-04-2020:51:01编程语言入门到精通Comments1,456 views字数 773阅读模式

可以在需要时使用嵌套的try块。 嵌套的try catch块就是这样一个块:其中一个try catch块在另一个try块中实现。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html

当一个代码块捕捉异常并且在该块内另一个代码语句也需要捕捉另一个异常时,就会有嵌套的try catch块的需要。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html

嵌套try块的语法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html

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

Kotlin嵌套try块示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html

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

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html

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文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18272.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/18272.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定