0Pricing
Kotlin Academy · Lesson

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

  1. try/catch/finally as an Expression
  2. Creating Custom Exception Classes
  3. runCatching and Result
  4. Re-throwing and Exception Chaining
← Back to Kotlin Academy