How to Use try as Expression in Kotlin: Simple Guide
In Kotlin,
try can be used as an expression that returns a value. You write try with catch blocks and the whole block returns the last expression inside it, allowing you to assign the result directly to a variable.Syntax
The try expression in Kotlin has this basic form:
tryblock: code that might throw an exception.catchblock(s): handle exceptions if they occur.- The entire
tryexpression returns the value of the last expression insidetryorcatch.
kotlin
val result = try { // code that might throw "Success" } catch (e: Exception) { "Failure" }
Example
This example shows how try as an expression returns a value depending on success or failure:
kotlin
fun parseNumber(text: String): Int {
return try {
text.toInt() // may throw NumberFormatException
} catch (e: NumberFormatException) {
-1 // return -1 if parsing fails
}
}
fun main() {
println(parseNumber("123")) // prints 123
println(parseNumber("abc")) // prints -1
}Output
123
-1
Common Pitfalls
One common mistake is using try as a statement without returning a value, which wastes its power as an expression. Another is forgetting that the try expression must return a value in all branches.
Also, avoid catching very broad exceptions unless necessary, as it can hide bugs.
kotlin
/* Wrong: try used as statement, no value returned */ fun wrongUsage(text: String) { try { val num = text.toInt() println(num) } catch (e: Exception) { println("Error") } } /* Right: try used as expression returning a value */ fun rightUsage(text: String): Int { return try { text.toInt() } catch (e: Exception) { -1 } }
Quick Reference
- try: Wrap code that might throw exceptions.
- catch: Handle exceptions and provide alternative results.
- try as expression: Returns the last expression from
tryorcatch. - Use it to assign results or return values cleanly.
Key Takeaways
Use try as an expression to return values from code that might throw exceptions.
The try block and catch blocks must return compatible types for the expression.
Assign the try expression result directly to variables or return it from functions.
Avoid using try only as a statement without returning a value.
Catch specific exceptions to handle errors clearly and avoid hiding bugs.