try/catch/finally as an Expression
Use try-catch as an expression to return values from error-prone code.
try/catch/finally as an Expression is a free Kotlin Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
Frequently asked questions
Is the “try/catch/finally as an Expression” lesson free?
Yes — the full text of “try/catch/finally as an Expression” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.
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; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
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
- try/catch/finally as an Expression
- Creating Custom Exception Classes
- runCatching and Result
- Re-throwing and Exception Chaining