Although we have seen the Exceptions provided by Kotlin. But sometimes, we need to create our own Exception.
And luckily, Kotlin provides an Exception, that you can inherit and define your own exception.
Let us see, how we can achieve with the below example.
fun main() { var number = 23 if (number < 50) { throw Exception("Number cannot be less than 50") } else { println("Number is greater than 50") } }
So, we have defined our custom exception that if a number is less than 50. An exception will be raised.
And all we have done is used the throw keyword with the Exception class to raise a custom exception.
throw Exception("Number cannot be less than 50")
So, in the above code we have defined a variable number and initialise it with the number 23.
var number = 23
Then we have checked, if the value of number is less than 50 or not.
if (number < 50) { throw Exception("Number cannot be less than 50") }
And in this case the value of number is less than 50. So, the exception is triggered, raising the exception using the throw keyword.
throw Exception("Number cannot be less than 50")
And we get the below exception as output.
Exception in thread "main" java.lang.Exception: Number cannot be less than 50