Kotlin Academy · Lesson

try/catch/finally as an Expression

Use try-catch as an expression to return values from error-prone code.

Lesson 1 of 413 steps

try/catch/finally as an Expression is a free Kotlin Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

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}")
    }
}

try Returns a Value

Assign the result of a try/catch to a variable. The value is whatever the matched block yields.

fun main() {
    val n: Int = try {
        "42".toInt()
    } catch (e: NumberFormatException) {
        -1
    }
    println(n) // 42
}

try in a Function Body

You can use try as the body of an expression-bodied function.

fun parseOrDefault(s: String, default: Int): Int = try {
    s.toInt()
} catch (e: NumberFormatException) {
    default
}
fun main() {
    println(parseOrDefault("42", 0))   // 42
    println(parseOrDefault("abc", 0))  // 0
}

Multiple catch Clauses

List multiple catch clauses for different exception types. The first match wins.

fun main() {
    val result: String = try {
        val list = listOf(1)
        list[5].toString()
    } catch (e: IndexOutOfBoundsException) {
        "index out of bounds"
    } catch (e: Exception) {
        "other error"
    }
    println(result)
}

finally Block

finally always runs — used for cleanup. It does NOT affect the return value of the try expression.

fun main() {
    val n: Int = try {
        "42".toInt()
    } catch (e: NumberFormatException) {
        -1
    } finally {
        println("cleanup runs")
    }
    println("value = $n")
}

try with Multiple Statements

Use a block with multiple statements; the value is the last expression.

fun main() {
    val result: String = try {
        val n = 10 / 2
        val s = "Result is $n"
        s.uppercase()
    } catch (e: Exception) {
        "ERROR"
    }
    println(result) // RESULT IS 5
}

Catching Multiple Types

Kotlin doesn't support Java's multi-catch syntax (catch (A | B)). Use a common supertype or separate catch clauses.

fun parse(s: String): Int = try {
    s.toInt()
} catch (e: RuntimeException) { // covers NumberFormatException etc.
    -1
}
fun main() {
    println(parse("42"))
    println(parse("nope"))
}

Order of catch Matters

List specific exceptions before their supertypes — otherwise the supertype catches first.

fun main() {
    try {
        throw NumberFormatException("oops")
    } catch (e: NumberFormatException) {
        println("specific: ${e.message}")
    } catch (e: Exception) {
        println("generic")
    }
}

Returning from try

You can return early from inside try — the finally block still runs.

fun process(x: Int): String {
    return try {
        require(x > 0) { "must be positive" }
        "ok: $x"
    } catch (e: IllegalArgumentException) {
        "error: ${e.message}"
    } finally {
        println("processing done")
    }
}
fun main() {
    println(process(5))
    println(process(-1))
}

Anti-Pattern: Empty catch

Empty catch blocks hide errors. At minimum log the exception or rethrow.

fun main() {
    try {
        "abc".toInt()
    } catch (e: NumberFormatException) {
        // BAD: silently swallow
    }
    println("continued")
}

Quick Check

In Kotlin, what does a try/catch expression evaluate to?

Recap

try/catch is an expression: it returns a value. List specific exceptions before supertypes, use finally for cleanup, and avoid empty catch blocks. Use as a function body or to assign a default on error.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “try/catch/finally as an Expression” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “try/catch/finally as an Expression”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

What will I learn in “try/catch/finally as an Expression”?

Use try-catch as an expression to return values from error-prone code. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “try/catch/finally as an Expression” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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