📜  Kotlin多重捕获块

📅  最后修改于: 2021-01-05 07:32:25             🧑  作者: Mango

Kotlin多重捕获块

我们可以在代码中使用多个catch块。当我们在try块中使用不同类型的操作时,会使用Kotlin多个catch块,这可能会在try块中导致不同的异常。

Kotlin多重捕获块示例1

让我们看一下多个catch块的示例。在此示例中,我们将执行不同类型的操作。这些不同类型的操作可能会生成不同类型的异常。

 fun main(args: Array){
    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块从最特定的位置放置到一般位置,即,在捕获Exception之前必须先捕获ArithmeticException。

当我们从一般异常捕获到特定异常时会发生什么?

它将生成警告。例如:

让我们修改上面的代码,并将catch块从一般异常放置到特定异常。

fun main(args: Array){
    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...