The try block in Kotlin can work as an expression. It can return a value just like any other expression, the returned value can be stored in a variable. In this guide, we will learn how to use try as an expression in Kotlin.
Kotlin try as an expression example
In the following example try block is working as an expression, the value returned by try can be stored in the variable as shown in the following example.
fun main(args: Array<String>) { var website = "Beginnersbook.com" var num = try { website.toInt() } catch (e: NumberFormatException) { "Cannot convert String to integer" } println(num) var number = "100" var num2 = try { number.toInt() } catch (e: NumberFormatException) { "Cannot convert String to integer" } println(num2) }
Output:
Leave a Reply