Kotlin throw 关键字用于引发显式异常。它用于引发自定义异常。
要抛出异常对象,无涯教程将使用throw-expression。
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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)