原文: https://beginnersbook.com/2019/03/kotlin-nested-try-catch-block/
当try catch块出现在另一个try catch块中时,它被称为嵌套的try catch块。如果在内部try catch块中没有处理内部try catch块中发生任何异常,则检查外部try catch块的catch块是否存在该异常。
嵌套try catch块的语法
try{//codetry{//code}catch{//handler}}catch{//handler}
嵌套的Try-Catch块示例
在下面的示例中,内部try块中存在异常,但是在内部catch块中未处理发生的异常(ArithmeticException),因此检查外部catch块是否存在此异常,因为外部catch块正在处理此异常,代码对于ArithmeticException,执行外部的catch块。
try块中可以有多个try catch块,内部try块内也可以有try catch块。这里要注意的唯一事情是,如果在子try块中没有处理异常,那么将检查父try catch块的处理程序是否发生了异常。
fun main(args: Array<String>) {try {val num = 100 / 5println(num)try {val num2 = 100 / 0println(num2)}catch(e: NumberFormatException){println("Number Format Exception")}}catch(e: ArithmeticException){println("Arithmetic Exception")}}
输出:

