Created
January 8, 2022 21:28
-
-
Save optimho/66264c7d719e61a41dd1cc7460f0bb15 to your computer and use it in GitHub Desktop.
Make use of the finally satement in the code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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