androidengineers.Book a session

Exception Handling and Error Management

Practice: Robust Error Handling

exercise35 minMedium

Parse a batch without losing error locations

Build a parser for lines containing positive study-minute values. Report each invalid line's one-based number while preserving valid records in order. Decide explicitly whether the caller accepts partial results.

data class Batch(val values: List<Int>, val invalidLines: List<Int>)

fun parseBatch(lines: List<String>): Batch {
    val values = mutableListOf<Int>()
    val invalid = mutableListOf<Int>()
    lines.forEachIndexed { index, line ->
        val value = line.trim().toIntOrNull()
        if (value == null || value <= 0) invalid.add(index + 1)
        else values.add(value)
    }
    return Batch(values.toList(), invalid.toList())
}

Parsing is independent from saving. An all-or-nothing importer can reject a batch with any invalid lines before modifying storage. A partial importer can display a report before accepting valid records.

Acceptance checks

Input 25, bad, -1, 50 yields values [25, 50] and invalid lines [2, 3]. Test empty input, whitespace, integer overflow, and all-invalid input.

Extension: return error reasons as well as line numbers without logging raw private data.

Reference: Exceptions and validation

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Practice: Robust Error Handling | Kotlin Core Programming | Android Engineers