Skip to content

Exceptions ​

kotlin
// throw, try/catch/finally, custom exceptions, try as an expression, runtime failures as exceptions.

class AppException(val code: Int, message: String) : Exception(message)

fun risky(n: Int): Int {
    if (n < 0) throw IllegalArgumentException("negative: $n")
    if (n == 0) throw AppException(404, "zero")
    return 100 / n
}

fun attempt(n: Int): String {
    return try {
        "ok ${risky(n)}"
    } catch (e: IllegalArgumentException) {
        "bad argument (${e.message})"
    } catch (e: AppException) {
        "app error ${e.code}: ${e.message}"
    } finally {
        println("finally for $n")
    }
}

fun main() {
    println(attempt(4))
    println(attempt(-1))
    println(attempt(0))

    // Runtime failures are ordinary exceptions, as on the JVM.
    val zero = 0
    try {
        println(10 / zero)
    } catch (e: ArithmeticException) {
        println("caught: ${e.message}")
    }
    try {
        val s: String? = null
        println(s!!.length)
    } catch (e: NullPointerException) {
        println("caught NPE")
    }
    try {
        check(zero > 0) { "zero is not positive" }
    } catch (e: IllegalStateException) {
        println(e.message)
    }
}

Output:

text
finally for 4
ok 25
finally for -1
bad argument (negative: -1)
finally for 0
app error 404: zero
caught: / by zero
caught NPE
zero is not positive

Notes ​

  • Exceptions use an error-return convention, not unwinding: a function that throws stores the exception in a thread-local slot and returns a dummy value; callers test the slot after every call that can throw. See Exceptions internals.
  • The runtime provides the standard exception classes (Throwable, Exception, RuntimeException, IllegalArgumentException, IllegalStateException, NullPointerException, ArithmeticException, ClassCastException, IndexOutOfBoundsException, NoSuchElementException, NumberFormatException, ...). Your own classes can extend them.
  • An exception that escapes main prints Exception in thread "main" ... to stderr and exits with status 1 (finally blocks still run).
  • There are no stack traces, printStackTrace() prints toString(), and suppressed exceptions are not recorded.

Released under the Apache License 2.0.