Kotlin / Editorial solution guide

Diagnose numeric parsing failures

Distinguish invalid numeric text from domain validation.

About 2 min readContent reviewed

Read-only knowledge base · No public comments

Recognize the symptoms

Numeric conversion throws or returns null for external text.

Understand the likely causes

  • The text does not match the accepted syntax or exceeds the target range.

Capture the input

Capture the exception and the input boundary that supplied the text, using a synthetic value in the reproduction. Record whether the input is empty, contains whitespace or nondigits, or exceeds the Int range. A parsing failure is different from a successfully parsed number outside the application’s allowed range. Preserve the original call path and avoid logging private input.

Inspect conversion rules

String.toInt expects a valid integer representation and throws when conversion fails. String.toIntOrNull returns null for invalid decimal text or a value outside the Int range; whitespace is not silently accepted by that function. Decide whether trimming is part of the input contract before applying it. A non-null parsed result still needs domain validation, such as a nonnegative count or an upper limit.

Keep parsing and domain validation as separate steps so the caller can explain the relevant failure. If the interface accepts localized numbers or a nondecimal format, document and test a parser designed for that format rather than assuming the decimal helper understands it. Preserve the original input only as long as needed for safe local diagnosis.

Handle invalid input

For expected invalid input, use toIntOrNull and handle null at the boundary that can report a useful error. The example parses a fixed valid value and prints it only after a null check. Do not replace null with zero unless the domain explicitly defines that fallback. If callers must distinguish syntax failure from overflow, use a parsing strategy that preserves the required distinction.

kotlin A checked conversion
fun main() {
    val value = "42".toIntOrNull()
    if (value != null) println(value) else println("invalid")
}
Expected output
42

The valid text parses to a non-null Int.

Verify boundary cases

Test valid zero, an ordinary value, empty text, whitespace under the chosen policy, nondigits, and a value beyond Int range. Test the application’s own endpoints separately. Verify that rejected input cannot update state and that valid zero is not mistaken for absence. Repeat the original operation in its actual entry point; an isolated parse alone does not establish that the application applies the same policy.

Verify the fix

Valid values parse, invalid values follow the documented error path, and zero remains a valid value when allowed.

Keep it from recurring

  • Document whitespace, range, and error behavior and test boundaries.

Official references