4、异常处理

异常类

我们的每一个异常也是一个类,他们都继承自Throwable

手动抛出异常

fun main() {
  	//Exception继承自Throwable类,作为普通的异常类型
    throw Exception("异常啦!")
}

自定义异常类

class TestException(message: String) : Exception(message)

fun main() {
    throw TestException("自定义异常")
}

异常处理

fun main() {
    println(test(1,0))
}

fun test(num1: Int,num2: Int): Int{
    try {
        return num1 / num2
    }catch (e: Exception){
        e.printStackTrace()
        return 0
    } finally {
        println("finally")
    }
}

try也可以当做一个表达式使用,这意味着它可以有一个返回值,也就是 catch 的最后一行,作为返回值。

所以对于上面的代码,我们可以改造一下

fun main() {
    println(test(1,0))
}

fun test(num1: Int,num2: Int): Int{
    return try {
        num1 / num2
    }catch (e: Exception){
        e.printStackTrace()
        0
    } finally {
        println("finally")
    }
}