try / catch / finally
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
// Basic form
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
| Syntax | Description |
|---|---|
| try { } catch (e: Type) { } | Catches and handles an exception. |
| finally { } | Always executes regardless of whether an exception occurred (used for resource cleanup, etc.). |
| throw exceptionObject | Throws an exception. |
| try expression | The 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
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")
}
// try expression — can return a value
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}")
}
}
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 contact us.