🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- What is
NumberFormatException? - Common Causes of
NumberFormatException - Handling
NumberFormatException - Examples of
NumberFormatException - Real-World Use Case
- 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment