Kotlin throw
关键字用于抛出显式异常。它用于抛出自定义异常。要抛出异常对象,将使用throw-expression
。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html
throw关键字的语法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html
throw SomeException()
Kotlin throw示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html
让我们来看一下throw
关键字的示例,此示例演示验证驾驶执照的年龄限制。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html
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")
}
执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html
Exception in thread "main" java.lang.ArithmeticException: under age
//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-throw-keyword.html#article-start文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html