Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Kotlin Dictionary

  1. Home
  2. Kotlin Dictionary
  3. try / catch / finally

try / catch / finally

Since: Kotlin 1.0(2016)

Kotlin handles exceptions using try, catch, and finally. Because try is an expression in Kotlin, you can concisely provide a default value when an exception occurs.

Syntax

try {
    // Code that may throw an exception
} catch (e: ExceptionType) {
    // Code to handle the exception
} finally {
    // Code that always runs, regardless of whether an exception occurred
}

// try expression (can return a value)
val result = try {
    string.toInt()
} catch (e: NumberFormatException) {
    -1 // Default value when an exception occurs
}

Syntax Overview

SyntaxDescription
try { } catch (e: Type) { }Catches and handles an exception.
finally { }Always executes regardless of whether an exception occurred (used for resource cleanup, etc.).
throw exceptionObjectThrows an exception.
try expressionThe last expression in the try block (or catch block) becomes the return value.
catch (e: IOException)Catches a specific exception type. You can write multiple catch blocks.

Sample Code

sample_try_catch_finally_kotlin.kt
fun divide(a: Int, b: Int): Int {
    if (b == 0) throw IllegalArgumentException("Cannot divide by zero")
    return a / b
}

fun main() {
    // Basic try-catch-finally
    try {
        println(divide(10, 2)) // 5
        println(divide(10, 0)) // An exception is thrown here
    } catch (e: IllegalArgumentException) {
        println("Error: ${e.message}") // Error: Cannot divide by zero
    } finally {
        println("finally always runs")
    }

    val n1 = try { "42".toInt() } catch (e: NumberFormatException) { -1 }
    val n2 = try { "abc".toInt() } catch (e: NumberFormatException) { -1 }
    println(n1) // 42
    println(n2) // -1 (default value when conversion fails)

    // Multiple catch blocks handle different exception types.
    try {
        val list = listOf(1, 2, 3)
        println(list[5]) // IndexOutOfBoundsException
    } catch (e: IndexOutOfBoundsException) {
        println("Index out of bounds: ${e.message}")
    } catch (e: Exception) {
        println("Other error: ${e.message}")
    }
}

The command looks like this:

kotlinc try_catch_finally_kotlin.kt -include-runtime -d try_catch_finally_kotlin.jar
java -jar try_catch_finally_kotlin.jar
5
Error: Cannot divide by zero
finally always runs
42
-1
Index out of bounds: Index 5 out of bounds for length 3

Notes

Unlike Java, Kotlin has no checked exceptions. All exceptions are unchecked, so you are never forced to catch them — but you should catch them when appropriate.

Using try as an expression lets you concisely provide a default value when an exception occurs. Combining it with ?.let or runCatching() enables a more functional style of error handling.

For precondition checks, see require() / check() / error().

If you find any errors or copyright issues, please .