📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
What is NumberFormatException?
NumberFormatException Class Diagram
Common Causes
Java NumberFormatException Example
In the below example, we are trying to parse the "100ABCD" string into an integer leads to NumberFormatException:package com.javaguides.corejava;
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String str1 = "100ABCD";
try {
int x = Integer.parseInt(str1); // Converting string with inappropriate format
int y = Integer.valueOf(str1);
} catch (NumberFormatException e) {
System.err.println("NumberFormatException caught!");
e.printStackTrace();
}
}
}
NumberFormatException caught!
java.lang.NumberFormatException: For input string: "100ABCD"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.javaguides.corejava.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)
Handling NumberFormatException
Best Practices
- Avoid blind trust in external data.
- Always assume the possibility of incorrect formats and validate data before processing.
- Consider setting up input masks or formats in user interfaces to guide users into inputting data in the correct format.
- When parsing multiple strings in a loop, it might be beneficial to log the failures but continue processing valid entries instead of terminating the whole process.
Comments
Post a Comment
Leave Comment