Using the Try/Catch statement in Kotlin.
fun main() {
println(getNumber("22")) // returns 22
println(getNumber("22.5")) // returns 0
println(getNumber2("33") ?: "I can't print the result") // Use null return to determine output
println(getNumber2("33.5") ?: IllegalArgumentException("Number isn't an Int")) // Use null return to throw a different Exception
notImplementedYet("Yep")
}
// Don't have to declare the exceptions that Kotlin throws as it does not distinguish between checked and unchecked exceptions. Try/catch can be used as an expression.
fun getNumber(string: String): Int {
return try {
Integer.parseInt(string)
}
catch (e: NumberFormatException) {
0
}
finally {
println("I'm in the finally block") // Will print regardless of outcome. Prints before the result as it gets executed and then the function returns the result.
1 // Does not feature as the finally block is not involved in the execution of the function
}
}
//If you want to return null instead of throwing an exception:
fun getNumber2(string: String): Int? {
return try {
Integer.parseInt(string)
}
catch (e: NumberFormatException) {
null
}
finally {
println("I'm in the finally block")
}
}
// A developer might implement a function that will always throw an Exception since it has not been completed yet - as a reminder to themselves and other developers that code is incomplete:
fun notImplementedYet (something: String): Nothing { // Makes it clear to developers that this code will never return a value
throw IllegalArgumentException("Implement me!")
}
