The Analogy: The Flight Crew's Emergency Checklists
A flight crew runs the risky phases of a flight knowing that things can go wrong, so they wrap each phase in a set of standing emergency procedures. The attempted maneuver is the main task; the procedures are the responses held in reserve should something fail during it. Kotlin's try block is that attempted operation, and its catch blocks are the emergency procedures waiting alongside. What is distinctive in Kotlin is that try is an expression: the whole structure yields a value, either the normal result when the block succeeds or a substitute that a handler supplies when it does not, so error handling produces a value rather than merely diverting control.
Emergency checklists are ordered most-specific-first. The "engine fire" procedure sits above the general "unspecified warning" procedure, because if the generic one came first it would trigger on an engine fire too and the specific procedure would never be reached. Kotlin matches catch clauses top-down in exactly this way, so a broad catch (e: Exception) placed before catch (e: NumberFormatException) leaves the specific handler unreachable. Kotlin also declines to make the crew declare every conceivable failure in advance: it has no checked exceptions, so a function is never forced by the compiler to announce what it might throw.
Some steps run no matter what. The post-flight shutdown checklist -- fuel pumps off, switches safed -- is performed whether the flight was routine or an emergency, and never skipped. A finally block is that shutdown: it runs on the normal path, after a caught exception, and even while an uncaught one is propagating, which is why cleanup belongs there rather than being copied into each branch. Before the risky phase there are also preconditions to clear: the crew verifies its inputs and configuration and aborts at once if a value is wrong or the aircraft is not in a valid state. Kotlin's require guards arguments, check guards state, and error aborts outright, each throwing immediately when its condition fails.
The failure that endangers the aircraft is the crew that wires every warning to one generic "note it and carry on" response, swallowing an engine fire as though it were a spurious lavatory-smoke alert. The true fault is hidden and the aircraft flies on damaged. In code this is the catch-all that catches Exception -- or worse, Throwable -- and does nothing, quietly hiding real bugs behind a green light. The mirror-image failure is placing cleanup only on the success path and skipping the shutdown after an emergency, leaving fuel pumps running: resources leaked because finally was not used. Good handling is specific about what it catches and unfailing about what it cleans up.
Syntax or Core Structure
A try is an expression that returns the value of its block or of the matching catch. A finally runs regardless of outcome.
fun parseOr(text: String, fallback: Int): Int {
return try {
text.toInt()
} catch (e: NumberFormatException) {
fallback
} finally {
println("parse attempt done for '" + text + "'")
}
}
fun main() {
println("result " + parseOr("42", -1))
println("result " + parseOr("oops", -1))
}
Output:
parse attempt done for '42'
result 42
parse attempt done for 'oops'
result -1
The finally line prints before each result line because finally runs as the try expression completes, before the caller prints the returned value. For "42", text.toInt() succeeds and the try yields 42; finally prints its note, then the caller prints "result 42". For "oops", toInt throws NumberFormatException, the catch supplies the fallback -1, finally still runs, and the caller prints "result -1". The try expression's value is whichever branch completed, and finally never contributes to that value -- it runs for its side effect only.
Technical Depth: Hierarchy, Ordering, and Preconditions
The exception hierarchy and its helpers
Every thrown value is a Throwable. The common built-in exceptions and the standard functions that throw them are worth knowing by name.
| Type or function | Thrown when | Typical trigger |
|---|---|---|
IllegalArgumentException | an argument is invalid | require(cond) fails |
IllegalStateException | object state is invalid | check(cond) fails |
NumberFormatException | a string is not a number | "x".toInt() |
NullPointerException | a null was dereferenced | !! on null |
IndexOutOfBoundsException | an index is out of range | list[99] |
error(msg) | you abort unconditionally | any invariant break |
Exception and its subclasses are for recoverable conditions; Error (such as OutOfMemoryError) signals problems you should not try to catch. Kotlin treats all of them as unchecked.
Catch order: specific before general
Catch clauses are tried top to bottom, so the specific handler must come first or it can never run.
fun classify(text: String): String =
try {
val n = text.toInt()
"number " + n
} catch (e: NumberFormatException) {
"not a number"
} catch (e: Exception) {
"other error: " + e.message
}
fun main() {
println(classify("7"))
println(classify("seven"))
}
Output:
number 7
not a number
"7" parses to 7 and the try yields "number 7". "seven" throws NumberFormatException, which the first, most-specific catch handles, yielding "not a number"; the broader catch (e: Exception) never sees it. If those two clauses were swapped, the broad one would intercept the format error first and the specific handler would be dead code -- the ordering is what keeps each handler meaningful.
Preconditions with require, check, and error
The standard precondition functions throw the right exception type with one readable line, replacing hand-written if (...) throw.
fun withdraw(balance: Int, amount: Int): Int {
require(amount > 0) { "amount must be positive" }
check(balance >= amount) { "insufficient funds" }
return balance - amount
}
fun main() {
println(withdraw(100, 30))
val msg = try {
withdraw(100, 500)
} catch (e: IllegalStateException) {
"blocked: " + e.message
}
println(msg)
}
Output:
70
blocked: insufficient funds
require throws IllegalArgumentException when its condition is false, and check throws IllegalStateException; both take a lambda that builds the message only if they fail. The first call, withdraw(100, 30), passes both guards and returns 70. The second requests 500 against a balance of 100, so check fails, throwing IllegalStateException with "insufficient funds", which the catch turns into "blocked: insufficient funds". Using the right function documents intent: a bad argument versus a bad state.
throw is an expression of type Nothing
In Kotlin throw is an expression whose type is Nothing, the subtype of every type. That lets a throw sit on either branch of an if or on the right of an Elvis ?: without upsetting the type checker.
fun requirePositive(n: Int): Int =
if (n > 0) n else throw IllegalArgumentException("need positive, got " + n)
fun firstOr(list: List<Int>): Int =
list.firstOrNull() ?: throw NoSuchElementException("empty list")
fun main() {
println(requirePositive(5))
val msg = try {
requirePositive(-1)
} catch (e: IllegalArgumentException) {
"caught: " + e.message
}
println(msg)
println(firstOr(listOf(9, 8)))
}
Output:
5
caught: need positive, got -1
9
Because throw has type Nothing, the if in requirePositive type-checks even though one branch yields an Int and the other throws -- Nothing fits wherever Int is expected. requirePositive(5) returns 5; requirePositive(-1) throws, and the catch reports "caught: need positive, got -1". In firstOr, the Elvis operator returns the first element when present, so firstOr(listOf(9, 8)) yields 9; had the list been empty, the throw on the right would have fired instead. This is why throw composes cleanly inside expressions rather than requiring a separate statement.
Wrapping an exception with its cause
When you rethrow at a higher level, pass the original exception as the cause so the underlying failure is not lost. Every Throwable accepts a cause and exposes it through the cause property.
fun load(id: Int): String {
try {
if (id < 0) throw IllegalArgumentException("id " + id)
return "record-" + id
} catch (e: IllegalArgumentException) {
throw IllegalStateException("load failed", e)
}
}
fun main() {
println(load(7))
val info = try {
load(-3)
} catch (e: IllegalStateException) {
e.message + " / cause: " + e.cause?.message
}
println(info)
}
Output:
record-7
load failed / cause: id -3
load(7) succeeds and returns "record-7". load(-3) throws IllegalArgumentException("id -3"), which the inner catch wraps in an IllegalStateException("load failed", e) -- passing e as the cause. The outer catch reads both the wrapper's message and the preserved cause?.message, printing "load failed / cause: id -3". Wrapping raises the abstraction level of the error while keeping the original diagnostic attached, rather than discarding it.
Real World Example: Totalling a Price List
A checkout routine sums a list of price strings into a cents total. Worried about malformed input, the author wraps the whole calculation in a try that catches anything and returns 0 on failure -- a defensive move that feels safe.
fun totalCents(prices: List<String>): Int {
return try {
var sum = 0
for (p in prices) {
sum += p.toInt() // one bad entry aborts the whole loop
}
sum
} catch (e: Exception) {
0 // swallow everything, return 0
}
}
fun main() {
println("clean: " + totalCents(listOf("100", "250", "75")))
println("dirty: " + totalCents(listOf("100", "abc", "75")))
}
Output:
clean: 425
dirty: 0
On clean input the routine is correct: 100, 250, and 75 sum to 425. The loop parses each string, accumulates, and the try yields the total. For well-formed data the broad catch never fires and nothing looks wrong.
On dirty input the design collapses. The loop adds 100, then "abc".toInt() throws NumberFormatException, the broad catch intercepts it, and the function returns 0 -- discarding the 100 already counted and the valid 75 that was never reached. The caller receives 0, indistinguishable from an empty basket, with no signal that anything failed.
The genuine design flaw is twofold, and both halves are the swallow-everything anti-pattern from the analogy. First, the catch is far too broad: catching Exception would hide a genuine bug -- a null dereference, an arithmetic error -- just as readily as a bad price, wiring every warning to one generic response. Second, the handler discards information by returning a silent 0, so an error is impossible to tell from a legitimately empty total. And because the whole loop sits inside one try, a single malformed entry aborts the entire calculation rather than being isolated. The fix operates at the right granularity: parse each element with toIntOrNull() and decide per item -- skip it, default it, or collect the bad ones into an error to return to the caller -- and if a catch is used at all, narrow it to NumberFormatException so real bugs still surface. The limitation to remember is that a catch which returns a plausible-looking default is often worse than no catch, because it converts a loud failure into a quiet wrong answer.
Common Mistakes
- Catching
ExceptionorThrowablebroadly. A wide catch hides real bugs -- null dereferences, arithmetic errors -- alongside the condition you meant to handle. Catch the narrowest type that fits.
- Swallowing an exception silently. An empty
catchblock, or one that returns a plausible default without signalling failure, turns a loud crash into a quiet wrong answer. At minimum log or rethrow.
- Placing a general catch before a specific one. Catch clauses match top-down, so
catch (e: Exception)abovecatch (e: NumberFormatException)makes the specific handler unreachable dead code.
- Wrapping too much in one
try. A singletryaround a whole loop lets one bad element abort everything. Scope thetryto the smallest operation that can fail so failures stay isolated.
- Using exceptions for ordinary control flow. Throwing to signal a normal, expected outcome (like "not found") is slow and obscures intent. Return a nullable, a sealed result, or use
toIntOrNull-style APIs.
- Forgetting that
finallyalways runs. Cleanup placed only on the success path leaks resources when an exception fires. Put release logic infinally(or useusefor closeables).
- Returning from inside
finally. Areturnin afinallyblock overrides any value or exception from thetry, silently discarding results and errors. Never return fromfinally.
- Hand-writing precondition checks.
if (x < 0) throw IllegalArgumentException(...)is noisier and easier to get wrong thanrequire(x >= 0) { ... }. Userequire,check, anderror.
- Assuming Kotlin has checked exceptions. Nothing forces you to catch or declare a thrown type, which means an uncaught exception from a library call can surface anywhere. Read the API docs for what a call may throw.
Best Practices
- Catch the most specific exception type that you can actually handle, and let everything else propagate to a caller that can.
- Never swallow an exception in silence; handle it meaningfully, log it, or rethrow so the failure is visible.
- Scope each
tryto the smallest fallible operation, isolating failures instead of aborting an entire batch. - Put all cleanup in
finally(or theusefunction forCloseables) so resources are released on every path. - Use
requirefor argument validation,checkfor state validation, anderrorfor unconditional aborts, each with a clear message. - Prefer nullable returns,
...OrNullfunctions, or a sealed result type over exceptions for expected, recoverable outcomes. - Never
returnfrom afinallyblock, since it discards thetry's result and any in-flight exception. - Treat
tryas an expression where it clarifies code, letting a handler supply a fallback value directly.
Practice Exercises
- Write a function that returns a parsed
Intor a supplied default using atryexpression with acatch (e: NumberFormatException), and confirm both the success and fallback paths.
- Reproduce the swallow-everything flaw: sum a list of price strings inside one broad
try/catchreturning 0, show that one bad entry zeroes the total, then fix it with per-elementtoIntOrNullhandling.
- Add
requireandcheckguards to atransfer(from, to, amount)function, and demonstrate that a negative amount and an over-balance transfer throw the two different exception types.
- Write a
try/finally(nocatch) around an operation that throws, print a line infinally, and confirm from the output that thefinallyruns even though the exception propagates.