In this section, we will learn how to use try and throw statements as expressions in Kotlin.
Kotlin try statement are expressions:
When working with the try catch statement, be aware that the try-catch is capable of returning a value!
Basically, if no exception happens and the instructions of the try statement ran properly, then the value of the last expression in the try will return as a result of this block. But if an exception occurred, then the last expression of the catch handler will be used as the final result of invoking the try-catch.
Example: using try block as expression
fun main(){ var str:String = "332" val result = try { str.toInt() } catch (e: Exception) { null } if (result !=null){ println(result) }else{ println("The value of the result variable is null") } }
Output:
332
Here you can see that the value of the result
variable is a call to the try-catch statements.
So in the try block, the expression will run and if it succeeds without any exception, then its value will return and assign to the result
variable. But if an exception occurred, then the value in the catch handler which is null will return as a result.