Kotlin - Catch多个异常

Kotlin - Catch多个异常 首页 / Kotlin入门教程 / Kotlin - Catch多个异常

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

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

链接:https://www.learnfk.comhttps://www.learnfk.com/kotlin/kotlin-multiple-catch-block.html

来源:LearnFk无涯教程网

 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...

Note: 一次只发生一个异常,一次只执行一个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...

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据结构与算法之美 -〔王争〕

OpenResty从入门到实战 -〔温铭〕

研发效率破局之道 -〔葛俊〕

系统性能调优必知必会 -〔陶辉〕

如何看懂一幅画 -〔罗桂霞〕

实用密码学 -〔范学雷〕

打造爆款短视频 -〔周维〕

超级访谈:对话毕玄 -〔毕玄〕

手把手带你写一个 MiniTomcat -〔郭屹〕

好记忆不如烂笔头。留下您的足迹吧 :)