1. Handling Errors Deliberately

[THEORY]

[PREDICT]

Read the code carefully before you run it.

prediction.kt
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?

[TASK]

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.

task.kt
// TODO: parse every entry as an Int. If an entry is not a whole number, // throw an IllegalArgumentException whose message contains the bad entry. // Otherwise return the sum. fun sumPrices(rawPrices: List<String>): Int { var sum = 0 for (raw in rawPrices) { sum += raw.toIntOrNull() ?: 0 } return sum } fun main() { // TODO: print sumPrices(listOf("3", "5", "2")). }

Before you get a hint: what have you tried, and where exactly are you stuck?

[COMPREHENSION CHECK]

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?