try/catch/finally as an Expression
Use try-catch as an expression to return values from error-prone code.
try Is an Expression
In Kotlin, try/catch is an expression — it returns a value. The last expression in the try or catch block is the result.
Basic try/catch
Wrap code that may throw in a try block; handle exceptions in catch.
fun main() {
try {
val n = "abc".toInt()
println(n)
} catch (e: NumberFormatException) {
println("Not a number: ${e.message}")
}
}All lessons in this course
- try/catch/finally as an Expression
- Creating Custom Exception Classes
- runCatching and Result
- Re-throwing and Exception Chaining