Kotlin throw關鍵字

Kotlin throw關鍵字用於拋出顯式異常。它用於拋出自定義異常。要拋出異常對象,將使用throw-expression

throw關鍵字的語法

throw SomeException()

Kotlin throw示例

讓我們來看一下throw關鍵字的示例,此示例演示驗證駕駛執照的年齡限制。

fun main(args: Array<String>) {
    validate(15)
    println("code after validation check...")
}
fun validate(age: Int) {
    if (age < 18)
        throw ArithmeticException("under age")
    else
        println("eligible for drive")
}

執行上面示例代碼,得到以下結果 -

Exception in thread "main" java.lang.ArithmeticException: under age

上一篇: Kotlin finally塊 下一篇: Kotlin可空和非可空類型