๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Try-Catch

A try block holds code that may fail, and a catch block handles a problem from that code. The program keeps running after the catch block finishes.

Catching a failed conversion

The text abc cannot become a number, so toInt throws NumberFormatException. The catch prints the fallback line.

fun main() {
    try {
        val n = "abc".toInt()
        println(n)
    } catch (e: NumberFormatException) {
        println("Not a number")
    }
}

Finally after success

The conversion succeeds and prints 42. The finally block still runs and prints Done.

fun main() {
    try {
        val n = "42".toInt()
        println(n)
    } catch (e: NumberFormatException) {
        println("Not a number")
    } finally {
        println("Done")
    }
}

Finally after failure

The conversion fails and the catch prints its line. The finally block runs here too and prints Done.

fun main() {
    try {
        val n = "abc".toInt()
        println(n)
    } catch (e: NumberFormatException) {
        println("Not a number")
    } finally {
        println("Done")
    }
}

Try as an expression

The first try expression gives 42 from the try block. The second gives 0 from the catch block.

fun main() {
    val n = try {
        "42".toInt()
    } catch (e: NumberFormatException) {
        0
    }
    println(n)
    val m = try {
        "abc".toInt()
    } catch (e: NumberFormatException) {
        0
    }
    println(m)
}

Example

class LimitException : Exception("Value is too big")

fun checkValue(value: Int) {
    if (value > 100) {
        throw LimitException()
    }
    println("Value is $value")
}

fun main() {
    try {
        checkValue(150)
    } catch (e: LimitException) {
        println(e.message)
    } finally {
        println("Check finished")
    }
}

Key points

  • Use try to guard code that may fail
  • Use catch to handle a problem from the try block
  • A catch block names the kind of exception it handles
  • A finally block runs whether the try block failed or not
  • A try expression produces a value from the try block or the catch block

In this example, checkValue throws LimitException for the value 150. The catch prints the stored message Value is too big. The finally block prints Check finished after the catch.

Note

A catch block that names one exception type does not catch other types.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

When does a finally block run?