Kotlin throw关键字,在这个简短的指南中,我们将学习如何在 Kotlin 中使用throw关键字抛出异常。
Kotlin throw关键字示例
在下面的示例中,我们使用throw关键字抛出异常。在这里我抛出了父Exception类,你可以抛出任何异常,如ArithmeticException,ArrayIndexOutOfBoundsException等。
fun main(args: Array<String>) {
print("Enter your name: ")
val name = readLine()
try{
if (name == "Chaitanya"){
throw Exception("You don't have access")
}
else
{
println("Welcome! You have access")
}
}
catch (e: Exception){
println(e.message)
}
}
输出:

极客教程