Java NumberFormatException
Example
Convert text that is not a number to an int, and catch the exception:
public class Main {
public static void main(String[] args) {
String text = "Hello";
try {
int myNum = Integer.parseInt(text);
System.out.println(myNum);
} catch (NumberFormatException e) {
System.out.println("The text is not a valid number.");
}
}
}
Definition and Usage
A NumberFormatException happens when you try to convert a string to a number, but the string is not a valid number, for example with Integer.parseInt("Hello").
A decimal number also causes it when you convert to a whole number: Integer.parseInt("3.5") throws this exception.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions