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.