Kotlin教程:throw-expression关键字

Kotlin throw关键字用于抛出显式异常。它用于抛出自定义异常。要抛出异常对象,将使用throw-expression

throw关键字的语法

throw SomeException()
Kotlin

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")  
}
Kotlin

执行上面示例代码,得到以下结果 -

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

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-throw-keyword.html#article-start

THE END