Kotlin try...catch块

Kotlin try...catch块

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

使用catch块的try语法

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

使用finally块的try语法

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

try catch语法与finally块

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

没有异常处理的问题

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

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

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

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

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

异常处理解决方案

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

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

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

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

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

Kotlin try块作为表达式

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

Kotlin try作为表达的示例

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

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

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

10

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

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

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

0

Kotlin多个catch块示例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块必须从最具体到一般放置,即ArithmeticExceptioncatch必须在Exceptioncatch之前。

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

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

目录

数组

字符串

注解

反射