try expression
- Kotlin course
- Beginner
- Lesson 103/116
- 5 min
Learn to use try as an expression in Kotlin.
try as an expression: returns a value
In Kotlin try is an expression; it yields a value. The catch block can also return a value; that lets you give a fallback.
val n = try {
"42".toInt()
} catch (e: NumberFormatException) {
0
}
// n = 42On success the last line of the try block, on error the last line of the catch block is the result. This builds a flow similar to if/else. The result can be assigned directly to a variable.
Nullable results in try expressions
If the catch block returns null, the result may be null. The variable then becomes nullable; safe access is needed.
val n: Int? = try {
"abc".toInt()
} catch (e: NumberFormatException) {
null
}
println(n ?: -1) // -1The Elvis operator ?: gives a fallback for a null value. This lets you handle nullable results safely. This approach makes it easy to silently fall back when a conversion fails.
Practice Convert a string to a number
With a try expression, call "42".toInt(); catch NumberFormatException and return 0. Assign the result to val n and print it with println.
Starter code
fun main() {
// Convert a string with a try expression; fall back to 0, print the result
}Sample solution
fun main() {
val n = try {
"42".toInt()
} catch (e: NumberFormatException) {
0
}
println(n)
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does `val n = try { x.toInt() } catch (e) { 0 }` do?
- It writes 0 to n
- It writes null to n
- It writes the try value to n Correct answer
- It gives a compile error
Explanation: On no error the try value, on error the catch 0 goes to n.
2 Fill in the blank: try expression
val n = ____ { "42".toInt() } catch (e: NumberFormatException) { 0 }
val n = try { "42".toInt() } catch (e: NumberFormatException) { 0 }
Explanation: the try expression yields a value.
3 Match part to role
| Term | Meaning |
|---|---|
try { } |
Trial |
catch { } |
Fallback value |
val n = |
Assignment |
.toInt() |
Conversion |