NumberFormatException in Java
The NumberFormatException is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is not appropriate or illegal. By illegal format, it is meant that if you are trying to parse a string to an integer but the String contains a boolean value, it is of illegal format. For example - if we try to parse a string to integer but the string is null.
It is an unchecked exception. It is a subclass of IllegalArgumentException and implements the Serializable interface.
Constructors of NumberFormatException
Example of NumberFormatException
Common reasons for NumberFormatException
Since NumberFormatException occurs due to the inappropriate format of string for the corresponding argument of the method which is throwing the exception, there can be various ways of it. A few of them are mentioned as follows-
How to avoid NumberFormatException?
The NumberFormatException is basically caused because the input string is not well formatted or illegal while parsing into a numerical value. So, to avoid this exception, the input string provided has to be well formatted.
To have a valid and well-formatted string, first of all, check whether the input string is not null. Then, check for unnecessary spaces and trim out all of them after that put several checks to verify that argument string matches the type of the method which we are using for parsing the string. If the method is ParseInt(), check that the string is has an integer value and likewise for all other methods do the required checks.
In order to prevent a Java program from generating a NumberFormatException, it is always a good practice to enclosed the lines of code which can throw this exception in a try-catch block as shown below-