Skip to content

Instantly share code, notes, and snippets.

@optimho
Created January 8, 2022 21:28
Show Gist options
  • Select an option

  • Save optimho/66264c7d719e61a41dd1cc7460f0bb15 to your computer and use it in GitHub Desktop.

Select an option

Save optimho/66264c7d719e61a41dd1cc7460f0bb15 to your computer and use it in GitHub Desktop.
Make use of the finally satement in the code
import java.lang.Exception
import java.time.temporal.TemporalAmount
import kotlin.reflect.typeOf
fun main(args: Array<String>) {
val p:Person = Person("Michael", 18)
println("Try Check if age throws an exception")
try {
//try to run this code
checkAge(p)
println("Its OKay all good")
println("and age is ${p.age}")
} catch (ex: Exception){
// only runs if there is a problem
println(" yip there is a problem")
println("Kid is only ${p.age} years old")
} finally {
//always runs
println("Do some cleanup operations so that the fault exits gracefully")
}
}
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