Kotlin教程:try…catch块异常处理解决方案

2023年 7月 12日 30.2k 0

Kotlin try-catch块用于代码中的异常处理。 try块包含可能抛出异常的代码,catch块用于处理异常,必须在方法中写入此块。 Kotlin try块必须跟随catch块或finally块或两者。

使用catch块的try语法

try{    
//code that may throw exception    
}catch(e: SomeException){  
//code that handles exception  
}

Kotlin

使用finally块的try语法

try{    
//code that may throw exception    
}finally{  
// code finally block  
}

Kotlin

try catch语法与finally块

try {  
    // some code  
}  
catch (e: SomeException) {  
    // handler  
}  
finally {  
    // optional finally block  
}

Kotlin

没有异常处理的问题

下面来看看一个未处理的异常的例子。

fun main(args: Array){  
    val data = 20 / 0   //may throw exception  
    println("code below exception ...")  
}

Kotlin

上面的程序生成一个异常,导致低于的异常代码的其余部分不可执行。

执行上面示例代码,得到以下结果 -

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionHandlingKt.main(ExceptionHandling.kt:2)

Shell

异常处理解决方案

通过使用try-catch块来看到上述问题的解决方案。

fun main(args: Array){  
    try {  
        val data = 20 / 0  //may throw exception  
    } catch (e: ArithmeticException) {  
        println(e)  
    }  
    println("code below exception...")  
}

Kotlin

执行上面示例代码,得到以下结果 -

java.lang.ArithmeticException: / by zero
code below exception...

Shell

在实现try-catch块之后的上述程序中,执行异常下面的其余代码。

Kotlin try块作为表达式

使用try块作为返回值的表达式。 try表达式返回的值是try块的最后一个表达式或catch的最后一个表达式。 finally块的内容不会影响表达式的结果。

Kotlin try作为表达的示例

下面来看一下try-catch块作为返回值的表达式的示例。 在此示例中,Int的字符串值不会生成任何异常并返回try块的最后一个语句。

fun main(args: Array){  
val str = getNumber("10")  
    println(str)  
}  
fun getNumber(str: String): Int{  
    return try {  
        Integer.parseInt(str)  
    } catch (e: ArithmeticException) {  
        0  
    }  
}

Kotlin

执行上面示例代码,得到以下结果 -

10

Shell

修改上面生成异常的代码并返回catch块的最后一个语句。

fun main(args: Array){
    val str = getNumber("10.5")
    println(str)
}
fun getNumber(str: String): Int{
    return try {
        Integer.parseInt(str)
    } catch (e: NumberFormatException) {
        0
    }
}

Kotlin

执行上面示例代码,得到以下结果 -

0

Shell

Kotlin多个catch块示例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...")  
}

Kotlin

执行上面示例代码,得到以下结果 -

arithmetic exception catch
code after try catch...

Shell

注意 :一次只发生一个异常,并且一次只执行一个catch块。

规则: 所有catch块必须从最具体到一般放置,即ArithmeticExceptioncatch必须在Exceptioncatch之前。

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

它会产生警告。 例如: 修改上面的代码并将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...")
}

Kotlin

编译时输出

warning : division by zero
a[5] = 10/0

Shell

运行时输出

parent exception catch
code after try catch...

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-try-catch.html#article-start

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论