跳过正文
  1. 文章/
  2. Kotlin/
  3. Kotlin高级/

4、异常处理

·276 字·1 分钟· loading · loading · ·
Kotlin Kotlin高级
GradyYoung
作者
GradyYoung
Kotlin高级 - 点击查看当前系列文章
§ 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")
    }
}
Kotlin高级 - 点击查看当前系列文章
§ 4、异常处理 「 当前文章 」