LAST UPDATED: AUGUST 10, 2020
Kotlin throw Keyword
In this tutorial we will learn about the throw
keyword in Kotlin and how we can use it to throw exceptions.
The Kotlin throw
keyword is used to throw an exception explicitely. We can also create our own custom exception and throw it using the Kotlin throw
keyword.
Kotlin throw
Keyword
The syntax of the throw
keyword is:
throw SomeException("Custom Exception Message")
As you can see in the example above, we can throw an exception along with some exception message which is propagated to the catch
block where we can use it to show the message to the end user.
Kotlin throw
Example
Let us throw an exception when the length of password entered by user is less than 3:
fun main() {
val userName: String = "Ninja"
val password: String = "ps"
if(password.length <= 3){
throw Exception("The minimum length of password should be 3!!")
}
}
Exception in thread "main" java.lang.Exception: The minimum length of password should be 3!!
at FinallyKt.main(finally.kt:5)
at FinallyKt.main(finally.kt)
Just like the example above, we can use the throw
keyword to disrupt the flow of execution of the code and then handle the exception event generated using the catch
block.
Summary
In this tutorial, we saw how we can throw an exception explicitely. We can also create our custom exception by extending the Exception class, using inheritance.