Throw is used to force an exception that would otherwise not be thrown. This comes in handy for making your own logic which shouldn't accept values outside of a given parameter. Like "Try", "Throw" can be passed as a value.
fun PickaNumberBetweenOneAndOneHundred(number: Int)
{
if(number !in 1..100){
throw IllegalArgumentException("It said a number between 1 and 100 you dingus")
}
}
//Throw as an expression
fun percentConverter(decimal: Long): Long{
val percentage = if(decimal+>0 && decimal<=1){
decimal*100
}
else{
throw IllegalArgumentException("Decimal must be within bounds of 0 and 1")
}
return percentage
}
//Using Throw with an Elvis operator
fun printName(person: Person?){
val name: String = person.name ?: throw IllegalArgumentException("Everyone needs a name ya dingus")
println(name)
}
//Using the Nothing type to not continue beyond a call
fun fail(message: String): Nothing{
throw IllegalArgumentException(message)
}
fun printDoggoName(name: String?){
//will not execute beyond this line if null due to Nothing return Type
val doggoName = name ?: fail("Doggo Name required")
println(doggoName)
}