try as an Expression

try Returns a Value

Like if and when, try is an expression: its value is the last expression of the try block or of the catch block that ran. finally does not affect the value.

Example

fun toPrice(text: String): Double = try {
    text.replace(",", "").toDouble()
} catch (e: NumberFormatException) {
    0.0
}

fun main() {
    println(toPrice("1,299.50"))
    println(toPrice("free"))
    // Often simpler: the OrNull functions
    println("abc".toIntOrNull() ?: -1)
}

Output

1299.5
0.0
-1