在上一个教程中,我们学习了什么是异常处理。在本指南中,我们将看到try catch块的各种示例。我们还将看到如何使用try作为表达式。
try catch块的语法
try {//code where an exception can occur}catch (e: SomeException) {// handle the exception}finally {// optional block but executes always}
try块可以与多个catch块相关联,但是只能存在一个finally块。
Kotlin try catch块示例
在这个例子中,我们放置了可能导致try块内异常的代码。一旦异常发生在try块内,它就会查找处理发生的异常的相应catch块。由于在代码中发生了ArithmeticException并且在catch块中处理了相同的异常,因此执行catch块中的代码。
异常处理的主要优点是程序不会突然终止。在以下示例中,最后一个println语句println("Out of try catch block")在catch块之后执行。如果我们没有进行异常处理,则不会执行此语句,因为程序将在行var num = 100/0上终止
fun main(args: Array<String>) {try{var num = 100/0println(num)}catch(e: ArithmeticException){println("Arithmetic Error in the code")}println("Out of try catch block")}
输出:

Kotlin 没有catch块的try块
try块可以没有catch块,但在这种情况下必须存在finally块。 总之,你可以说至少应该有一个catch或finally块。finally块是可选的,但是当没有catch块时,必须有一个finally块。
fun main(args: Array<String>) {try{var num = 10/5println(num)}finally{println("Finally block")}println("Out of try catch block")}
输出:
2Finally blockOut of try catch block
