In this kotlin tutorial, we will learn how to use kotlin throw keyword in exception. Why is throw keyword used?
How is throw keyword used? etc.
throw keyword is used to throw an exception explicitly. It is also used to throw a custom exception.
Syntax of throw keyword
throw ExceptionName("Some message")
Kotlin throw example
Let’s see an example to use throw keyword –
fun main(args: Array<String>) { validate(15) println("code after age validation check") } fun validate(age: Int) { if (age < 18) throw ArithmeticException("You are under age") else println("Eligible to vote in India") }
When you run the above program, you will output –
Exception in thread “main” java.lang.ArithmeticException: You are under age
Notice how we used throw keyword to throw ArithmeticException explicitly.
In kotlin, throw construct is an expression and can combine with other expressions as well.
Examples of throw as an expression
fun main(args: Array<String>) { val letter = 'c' val result = if (letter in 'a'..'z') letter else throw IllegalArgumentException("A letter must be between a to z") print(result) }
When you run the program, you will get output as below –
c
Exercises on throw in kotlin
fun main(args: Array<String>) { val letter = '1' val result = if (letter in 'a'..'z') letter else throw IllegalArgumentException("A letter must be between a to z") print(result) }
2. Guess the output of below program
fun main(args: Array<String>) { val letter = '111' val result = if (letter in 'a'..'z') letter else throw IllegalArgumentException("A letter must be between a to z") print(result) }
3. Guess the output of below program
fun main(args: Array<String>) { val letter = 'S' val result = if (letter in 'a'..'z') letter else throw IllegalArgumentException("A letter must be between a to z") print(result) }
That’s end of tutorial on kotlin throw exception tutorial.