可以在需要时使用嵌套的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