Exception Basics

try, catch, finally

An exception is an error that happens while the program runs (dividing by zero, a bad number format, a missing file). Wrap risky code in try; handle errors in catch; finally always runs (close resources, hide a loader).

Example

fun parseAge(text: String) {
    try {
        val age = text.toInt()
        println("Age is $age")
    } catch (e: NumberFormatException) {
        println("'$text' is not a number")
    } finally {
        println("-- done parsing '$text'")
    }
}

fun main() {
    parseAge("25")
    parseAge("twenty")
}

Output

Age is 25
-- done parsing '25'
'twenty' is not a number
-- done parsing 'twenty'

No Checked Exceptions

Unlike Java, Kotlin has no checked exceptions: the compiler never forces you to catch or declare them. That keeps code short, but you must think about which errors to handle. Catch the most specific types first.

Example

fun main() {
    val inputs = listOf("10", "0", "x")
    for (s in inputs) {
        try {
            println("100 / $s = ${100 / s.toInt()}")
        } catch (e: ArithmeticException) {
            println("Math error: ${e.message}")
        } catch (e: Exception) {
            println("Other error: ${e::class.simpleName}")
        }
    }
}

Output

100 / 10 = 10
Math error: / by zero
Other error: NumberFormatException

An Uncaught Exception

Example

If nobody catches it, the exception stops the program (in Android: the app crashes).

fun main() {
    val list = listOf(1, 2, 3)
    println("Before")
    println(list[5])
    println("Never printed")
}

Output

Before
Exception: java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3