January 2018
Intermediate to advanced
434 pages
14h 1m
English
The reason we can use try–catch as an expression is that both try and throw are expressions in Kotlin and hence can be assigned to a variable.
When you use try–catch as an expression, the last line of the try or catch block is returned. That's why, in the first example, we got 23 as the returned value and we got -1 in the second example.
Here, one thing to note is that the same thing doesn't apply to the finally block—that is, writing the finally block will not affect the result:
fun main(args: Array<String>) { val str="abc" val a:Int = try { str.toInt() } catch (e: NumberFormatException) { -1 } finally { -2 } println(a) }
Output: -1
As you can see, writing the finally block doesn't change anything.
Read now
Unlock full access