AnyCompiler

Exceptions, and a Closing Look

Like if, try in Kotlin is an expression — it produces a value, so a function can return try { ... } catch (e: Exception) { ... } directly, with the result of whichever branch actually ran becoming the function's return value. There's no checked-exception system to satisfy the way Java's is — you catch what you choose to catch.

fun safeDivide(a: Int, b: Int): Int {
    return try {
        a / b
    } catch (e: ArithmeticException) {
        0
    }
}

fun main() {
    println(safeDivide(10, 0))
}
Output
0

That's the foundation of Kotlin: null safety enforced by the type system instead of caught at runtime, val-by-default immutability, data classes for free structural equality, classes final by default until opened deliberately, sealed classes for compiler-checked exhaustiveness, and extension functions and higher-order functions for writing concise, expressive code. From here, the best next step is practice — pick a small program and build it, leaning on the compiler's static type checking (and its null-safety guarantees in particular) to catch mistakes as you go.

Practice exercise

Write a function safeDivide(a: Int, b: Int) that returns a / b using try as an expression, catching ArithmeticException to return 0. Call it with (10, 0).

← GenericsMore lessons coming soon