January 2018
Intermediate to advanced
434 pages
14h 1m
English
Let's write a simple program that takes in a number as an input and assigns its value to a variable. If the entered value is not a number, we catch the NumberFormatException exception and assign -1 to that variable:
fun main(args: Array<String>) { val str="23" val a: Int? = try { str.toInt() } catch (e: NumberFormatException) { -1 } println(a) }
This is the output:
Output: 23
Now, let's try something crazy and deliberately try to throw the exception:
fun main(args: Array<String>) { val str="abc" val a: Int? = try { str.toInt() } catch (e: NumberFormatException) { -1 } println(a) }
This is the output:
Output: -1
The usage of try–catch will help you a lot in edge cases as they can be used as an expression.
Read now
Unlock full access