无涯教程可以在代码中使用多个catch块。当无涯教程在try块中使用不同类型的操作时,会使用Kotlin多个catch块,这可能会在try块中导致不同的异常。
让无涯教程看一下多个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块调换位置。
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...
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)