In this short guide, we will learn how to throw a exception using throw keyword in Kotlin.
Kotlin throw keyword example
In the following example we are throwing an exception using throw keyword. Here I have thrown parent Exception class, you can throw any exception such as ArithmeticException, ArrayIndexOutOfBoundsException etc.
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) } }
Output:
Leave a Reply