Search⌘ K
AI Features

The try, catch, and finally Blocks

Explore how to use try catch blocks in Kotlin to handle exceptions effectively by returning alternative values or catching errors. Understand the purpose of finally blocks to always execute clean-up code or resource closing, even when exceptions occur.

Using try-catch as an expression

The try-catch structure can be used as an expression. It returns the result of a try block if no exception occurs. If an exception occurs and is caught, then the try-catch expression returns the result of the catch block.

Kotlin 1.5
fun main() {
val a = try {
1
} catch (e: Error) {
2
}
println(a) // 1
val b = try {
throw Error()
1
} catch (e: Error) {
2
}
println(b) // 2
}
...