Kotlin教程:throw-expression关键字

2020-04-2020:53:43编程语言入门到精通Comments1,537 views字数 518阅读模式

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

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-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

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18274.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/18274.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定