Kotlin Exception Handling: try, catch, finally and runCatching

Kotlin course · Advanced Kotlin · Lesson 44 of 51

Updated:

An exception is an error that happens while a program is running, such as dividing by zero, reading a missing file or converting "abc" to a number. If you don’t handle it, the program crashes. Exception handling lets you catch the error and react to it.

try and catch

fun main() {
    try {
        val number = "abc".toInt()
        println("Number: $number")
    } catch (e: NumberFormatException) {
        println("That's not a number: ${e.message}")
    }
    println("The program keeps running")
}

Output:

That's not a number: For input string: "abc"
The program keeps running

The code in try runs until something throws. Then Kotlin jumps to the matching catch block, and continues after it.

Catching different exceptions

fun divide(input: String, by: Int): String {
    return try {
        val n = input.toInt()
        "Result: ${n / by}"
    } catch (e: NumberFormatException) {
        "Invalid number"
    } catch (e: ArithmeticException) {
        "Can't divide by zero"
    }
}

fun main() {
    println(divide("20", 4))
    println(divide("x", 4))
    println(divide("20", 0))
}

Output:

Result: 5
Invalid number
Can't divide by zero

Put the most specific exceptions first. catch (e: Exception) catches almost everything, so it belongs last, if at all.

finally: always runs

fun main() {
    println("Opening connection")
    try {
        println("Sending data")
        throw IllegalStateException("Connection lost")
    } catch (e: IllegalStateException) {
        println("Error: ${e.message}")
    } finally {
        println("Closing connection")    // runs whether or not there was an error
    }
}

Output:

Opening connection
Sending data
Error: Connection lost
Closing connection

Use finally to release resources such as files, connections or locks. For files and streams, use { } closes them for you automatically.

try is an expression

Like if and when, try returns a value: the last expression of the try block, or of the catch block that ran:

fun main() {
    val input = "42x"
    val age = try { input.toInt() } catch (e: NumberFormatException) { 0 }
    println(age)

    // for simple conversions, toIntOrNull is even shorter
    println(input.toIntOrNull() ?: 0)
}

Output:

0
0

Throwing exceptions

fun withdraw(balance: Int, amount: Int): Int {
    if (amount <= 0) throw IllegalArgumentException("Amount must be positive")
    if (amount > balance) throw IllegalStateException("Insufficient balance")
    return balance - amount
}

fun main() {
    println(withdraw(1000, 300))
    try {
        withdraw(1000, 5000)
    } catch (e: IllegalStateException) {
        println(e.message)
    }
}

Output:

700
Insufficient balance

require, check and error

These standard functions throw for you, with clear intent:

FunctionThrowsUse for
require(cond) { msg }IllegalArgumentExceptionchecking arguments
check(cond) { msg }IllegalStateExceptionchecking an object’s state
error(msg)IllegalStateExceptioncode that should never be reached
requireNotNull(x)IllegalArgumentExceptionan argument that must not be null
class Player(val name: String) {
    var isLoggedIn = false

    fun play(level: Int) {
        require(level in 1..10) { "Level must be 1–10, was $level" }
        check(isLoggedIn) { "$name must log in first" }
        println("$name is playing level $level")
    }
}

fun main() {
    val p = Player("Zoya")
    try { p.play(3) } catch (e: IllegalStateException) { println(e.message) }
    p.isLoggedIn = true
    p.play(3)
    try { p.play(20) } catch (e: IllegalArgumentException) { println(e.message) }
}

Output:

Zoya must log in first
Zoya is playing level 3
Level must be 1–10, was 20

Custom exceptions

class PaymentDeclinedException(val code: String, message: String) : Exception(message)

fun pay(amount: Int) {
    if (amount > 10_000) throw PaymentDeclinedException("LIMIT", "Amount above daily limit")
    println("Paid ₹$amount")
}

fun main() {
    pay(500)
    try {
        pay(25_000)
    } catch (e: PaymentDeclinedException) {
        println("Declined [${e.code}]: ${e.message}")
    }
}

Output:

Paid ₹500
Declined [LIMIT]: Amount above daily limit

runCatching and Result

runCatching runs a block and wraps the outcome in a Result, which is either a success value or the exception. It’s handy for chaining:

fun parsePrice(text: String): Result<Int> = runCatching { text.trim().toInt() }

fun main() {
    val ok = parsePrice(" 499 ")
    val bad = parsePrice("free")

    println(ok.getOrNull())
    println(bad.getOrNull())
    println(bad.getOrDefault(0))

    bad.onFailure { println("Failed: ${it::class.simpleName}") }
    ok.map { it * 2 }.onSuccess { println("Double: $it") }
}

Output:

499
null
0
Failed: NumberFormatException
Double: 998

Kotlin has no checked exceptions

In Java, some exceptions must be declared with throws or caught. Kotlin doesn’t force this. You decide where handling makes sense. For Java code that calls your function, you can document it with @Throws(IOException::class).

Common mistakes

  • Catching Exception everywhere and ignoring it: you hide real bugs. Catch specific exceptions, and at least log them.
  • Using exceptions for normal flow: for expected situations, return null, a sealed result or use toIntOrNull() instead of throwing.
  • Swallowing CancellationException in coroutines: it’s how coroutines stop. If you catch Exception in coroutine code, rethrow CancellationException.

Exercise

Read “age” values from a list of strings. Skip invalid numbers, reject ages outside 0–120 with require, and report what happened to each.

fun parseAge(text: String): Int {
    val age = text.toInt()                       // may throw NumberFormatException
    require(age in 0..120) { "Age out of range: $age" }
    return age
}

fun main() {
    for (input in listOf("34", "abc", "150", "7")) {
        val message = try {
            "OK: ${parseAge(input)}"
        } catch (e: NumberFormatException) {
            "Not a number: \"$input\""
        } catch (e: IllegalArgumentException) {
            e.message ?: "Invalid"
        }
        println(message)
    }
}

Output:

OK: 34
Not a number: "abc"
Age out of range: 150
OK: 7

Note the order: NumberFormatException is a subclass of IllegalArgumentException, so it must be caught first.

FAQ

How do I handle exceptions in Kotlin?

Wrap the risky code in try { } catch (e: SomeException) { }. Add finally { } for clean-up that must always run.

Does Kotlin have checked exceptions?

No. You’re never forced to catch or declare exceptions.

What is runCatching in Kotlin?

A function that runs a block and returns a Result, so you can handle success and failure with getOrNull, getOrDefault, onSuccess and onFailure.

WhatsApp us📞 Call now