Kotlin throw关键字用于引发显式异常。它用于引发自定义异常。
要抛出异常对象, 我们将使用throw-expression。
throw关键字的语法
throw SomeException()
Kotlin抛出示例
让我们看一个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
评论前必须登录!
注册