Skip to content

Instantly share code, notes, and snippets.

@optimho
Last active January 8, 2022 21:11
Show Gist options
  • Select an option

  • Save optimho/998027b6c8c80b14841f2bef353ebf80 to your computer and use it in GitHub Desktop.

Select an option

Save optimho/998027b6c8c80b14841f2bef353ebf80 to your computer and use it in GitHub Desktop.
the try catch block to check and handle potential errors
import java.lang.Exception
import java.time.temporal.TemporalAmount
import kotlin.reflect.typeOf
fun main(args: Array<String>) {
val p:Person = Person("Michael", 10)
println("Try Check if age throws an exception")
try {
checkAge(p)
println("Its OKay all good")
println("and age is ${p.age}")
} catch (ex: Exception){
println(" yip there is a problem")
println("Kid is only ${p.age} years old")
}
}
private fun checkAge(p: Person){
if (p.age<12){
throw InvalidAgeException(p.age, "WTF dude")
}
}
class InvalidAgeException(val age: Int, override val message: String): IllegalArgumentException("Invalid Age: $age, $message"){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment