Kotlin NumberFormatException

Introduction

In Kotlin, NumberFormatException is a runtime exception that is thrown to indicate that an attempt to convert a string to a numeric type has failed because the string does not have an appropriate format. This exception is part of the Kotlin (and Java) standard library and typically occurs when parsing strings to numbers using functions like toInt(), toLong(), toFloat(), or toDouble().

Table of Contents

  1. What is NumberFormatException?
  2. Common Causes of NumberFormatException
  3. Handling NumberFormatException
  4. Examples of NumberFormatException
  5. Real-World Use Case
  6. Conclusion

1. What is NumberFormatException?

NumberFormatException is a subclass of IllegalArgumentException and is used to indicate that an attempt to convert a string to a numeric type has failed because the string does not represent a valid number.

Syntax

throw NumberFormatException("Exception message")

2. Common Causes of NumberFormatException

  • Parsing a string that contains non-numeric characters.
  • Parsing a string that is empty.
  • Parsing a string that represents a number outside the range of the target type.

Example

fun main() {
    val number = "123a".toInt() // This will cause NumberFormatException
}

3. Handling NumberFormatException

You can handle NumberFormatException using a try-catch block to prevent your program from crashing.

Example

fun main() {
    val number = "123a"
    try {
        val parsedNumber = number.toInt()
    } catch (e: NumberFormatException) {
        println("Caught a number format exception: ${e.message}")
    }
}

4. Examples of NumberFormatException

Example 1: Parsing an Invalid Integer

This example demonstrates how parsing a string with non-numeric characters causes NumberFormatException.

fun main() {
    val number = "123a"
    try {
        val parsedNumber = number.toInt()
    } catch (e: NumberFormatException) {
        println("Caught a number format exception: ${e.message}")
    }
}

Output:

Caught a number format exception: For input string: "123a"

Explanation:
This example catches and handles a NumberFormatException caused by parsing a string that contains non-numeric characters.

Example 2: Parsing an Empty String

This example demonstrates how parsing an empty string causes NumberFormatException.

fun main() {
    val number = ""
    try {
        val parsedNumber = number.toInt()
    } catch (e: NumberFormatException) {
        println("Caught a number format exception: ${e.message}")
    }
}

Output:

Caught a number format exception: For input string: ""

Explanation:
This example catches and handles a NumberFormatException caused by parsing an empty string.

Example 3: Parsing a String Outside the Range of Int

This example demonstrates how parsing a string representing a number outside the range of Int causes NumberFormatException.

fun main() {
    val number = "999999999999"
    try {
        val parsedNumber = number.toInt()
    } catch (e: NumberFormatException) {
        println("Caught a number format exception: ${e.message}")
    }
}

Output:

Caught a number format exception: For input string: "999999999999"

Explanation:
This example catches and handles a NumberFormatException caused by parsing a string that represents a number outside the range of Int.

Example 4: Using Safe Parsing Functions

This example demonstrates how to use safe parsing functions to avoid NumberFormatException.

fun safeParseInt(str: String): Int? {
    return try {
        str.toInt()
    } catch (e: NumberFormatException) {
        null
    }
}

fun main() {
    val number = "123a"
    val parsedNumber = safeParseInt(number)
    println("Parsed number: $parsedNumber") // Output: Parsed number: null
}

Explanation:
This example defines a safeParseInt function that returns null if the string cannot be parsed to an integer, avoiding NumberFormatException.

5. Real-World Use Case: Validating User Input

In a real-world scenario, you might need to validate user input to ensure it can be parsed to a number, providing appropriate feedback if it cannot.

Example: Validating User Input

fun parseUserInput(input: String): Int? {
    return try {
        input.toInt()
    } catch (e: NumberFormatException) {
        println("Invalid input: ${e.message}")
        null
    }
}

fun main() {
    val userInput = "42a"
    val number = parseUserInput(userInput)
    if (number != null) {
        println("Valid number: $number")
    } else {
        println("Please enter a valid number.")
    }
}

Output:

Invalid input: For input string: "42a"
Please enter a valid number.

Explanation:
This example defines a parseUserInput function that tries to parse user input to an integer and provides feedback if the input is invalid, avoiding NumberFormatException.

Conclusion

NumberFormatException in Kotlin is a runtime exception that occurs when an attempt to convert a string to a numeric type fails due to an inappropriate format. By understanding how to handle NumberFormatException using try-catch blocks and safe parsing functions, you can write more robust and error-resistant code. Proper validation of user input and careful handling of string-to-number conversions are crucial in real-world applications to ensure data integrity and prevent runtime exceptions.

Comments