我们可以在代码中使用多个catch块。当我们在try块中使用不同类型的操作时, 可能会使用try块中的异常, 因此会使用Kotlin多个catch块。
Kotlin多重捕获块示例1
让我们看一下多个catch块的示例。在此示例中, 我们将执行不同类型的操作。这些不同类型的操作可能会生成不同类型的异常。
fun main(args: Array<String>){
try {
val a = IntArray(5)
a[5] = 10 / 0
} catch (e: ArithmeticException) {
println("arithmetic exception catch")
} catch (e: ArrayIndexOutOfBoundsException) {
println("array index outofbounds exception")
} catch (e: Exception) {
println("parent exception class")
}
println("code after try catch...")
}
输出:
arithmetic exception catch
code after try catch...
注意:一次只发生一个异常, 一次只执行一个catch块。
规则:必须将所有catch块从最具体的到一般的放置, 即ArithmeticException的catch必须先于Exception的catch。
当我们从一般异常捕获到特定异常时会发生什么?
它将生成警告。例如:
让我们修改上面的代码, 并将catch块从一般异常更改为特定异常。
fun main(args: Array<String>){
try {
val a = IntArray(5)
a[5] = 10 / 0
}
catch (e: Exception) {
println("parent exception catch")
}
catch (e: ArithmeticException) {
println("arithmetic exception catch")
} catch (e: ArrayIndexOutOfBoundsException) {
println("array index outofbounds exception")
}
println("code after try catch...")
}
编译时输出
warning : division by zero
a[5] = 10/0
运行时输出
parent exception catch
code after try catch...
评论前必须登录!
注册