|
Question: Working with Java code, what is a NumberFormatException?
Answer: The best way to show a NumberFormatException is by example, so here's an example where I intentionally write bad Java code to throw a NumberFormatException:
package com.devdaily.javasamples;
public class ConvertStringToNumber
{
public static void main(String[] args)
{
try
{
String s = "FOOBAR";
int i = Integer.parseInt(s);
// this line of code will never be reached
System.out.println("int value = " + i);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
}
Because there's no way to convert the text FOOBAR into a number, trying to run this program will result in the following output:
java.lang.NumberFormatException: For input string: "FOOBAR"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at com.devdaily.javasamples.ConvertStringToNumber.main(ConvertStringToNumber.java:11)
So, a NumberFormatException is an Exception that might be thrown when you try to convert a String into a number, where that number might be an int, a float, or any other Java numeric type.
|