Read the code carefully before you run it.
fun loadCount(raw: String): Int {
return try {
raw.toInt()
} catch (e: NumberFormatException) {
0
}
}
fun main() {
println(loadCount("12"))
println(loadCount("abc"))
}
The second call prints 0. What is wrong with that, and where will the failure show up later?
The function sumPrices below turns every unparseable entry into zero, so a typo silently changes the total. Fix it: parse each entry as an Int, and if an entry is not a whole number, throw an IllegalArgumentException whose message contains the offending entry. For valid input it must still return the sum.
Before you get a hint: what have you tried, and where exactly are you stuck?
1. When should a function recover from an error instead of letting it propagate?
2. What is wrong with catching an exception and doing nothing in the catch block?
3. What makes an exception message useful?