NumberFormatException in Java
In this tutorial, we shall recreate the scenario for java.lang.NumberFormatException to happen, and explain how to fix this exception in detail.
The exception is thrown by many constructors/methods in the classes of java.lang package. Following are some of them :
- public Byte(String s) throws NumberFormatException (java doc link)
- public static byte parseByte(String s, int radix) throws NumberFormatException
- public static byte parseByte(String s) throws NumberFormatException
- public static Byte valueOf(String s, int radix) throws NumberFormatException
- public static Byte valueOf(String s) throws NumberFormatException
- public Integer(String s) throws NumberFormatException
- public static int parseInt(String s) throws NumberFormatException
There are situations defined for each method, where it could throw a NumberFormatException.
For instance “public static int parseInt(String s) throws NumberFormatException” when
- String s is null or length of s is zero.
- If the string s contains non numeric characters.
- Value of string s doesn’t represent an integer.
Let us investigate deeper as to how this Exception has come to picture, by running the following program.
NumberFormatExceptionExample.java
package com.mm;
/**
* @author tutorialkart.com
*/
public class NumberFormatExceptionExample {
public static void main(String[] args){
int i = Integer.parseInt("25k");
System.out.println(i);
}
}
We get the following java call stack in console as output.
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "25k"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at com.mm.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8)
We shall go into the stack, analyze one method after another, from bottom of the call stack
at com.mm.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:8):
7: public static void main(String[] args){
8: int i = Integer.parseInt("25k");
9: System.out.println(i);
10:}
at java.lang.Integer.parseInt(Integer.java:527) :
Integer.parseInt(“25k”)
526: public static int parseInt(String s) throws NumberFormatException {
527: return parseInt(s,10);
528: }
at java.lang.Integer.parseInt(Integer.java:492) :
parseInt(s,10)
444: public static int parseInt(String s, int radix)
445: throws NumberFormatException
446: {
447: /*
448: * WARNING: This method may be invoked early during VM initialization
449: * before IntegerCache is initialized. Care must be taken to not use
450: * the valueOf method.
451: */
452:
453: if (s == null) {
454: throw new NumberFormatException("null");
455: }
456:
457: if (radix < Character.MIN_RADIX) { 458: throw new NumberFormatException("radix " + radix + 459: " less than Character.MIN_RADIX"); 460: } 461: 462: if (radix > Character.MAX_RADIX) {
463: throw new NumberFormatException("radix " + radix +
464: " greater than Character.MAX_RADIX");
465: }
466:
467: int result = 0;
468: boolean negative = false;
469: int i = 0, len = s.length();
470: int limit = -Integer.MAX_VALUE;
471: int multmin;
472: int digit;
473:
474: if (len > 0) {
475: char firstChar = s.charAt(0);
476: if (firstChar < '0') { // Possible leading "+" or "-"
477: if (firstChar == '-') {
478: negative = true;
479: limit = Integer.MIN_VALUE;
480: } else if (firstChar != '+')
481: throw NumberFormatException.forInputString(s);
482:
483: if (len == 1) // Cannot have lone "+" or "-"
484: throw NumberFormatException.forInputString(s);
485: i++;
486: }
487: multmin = limit / radix;
488: while (i < len) {
489: // Accumulating negatively avoids surprises near MAX_VALUE
490: digit = Character.digit(s.charAt(i++),radix);
491: if (digit < 0) {
492: throw NumberFormatException.forInputString(s);
493: }
494: if (result < multmin) {
495: throw NumberFormatException.forInputString(s);
496: }
497: result *= radix;
498: if (result < limit + digit) {
499: throw NumberFormatException.forInputString(s);
500: }
501: result -= digit;
502: }
503: } else {
504: throw NumberFormatException.forInputString(s);
505: }
506: return negative ? result : -result;
507: }
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) :
NumberFormatException.forInputString(s);
64: static NumberFormatException forInputString(String s) {
65: return new NumberFormatException("For input string: \"" + s + "\"");
66: }
This is the String “For input string: “25k” ” at the top of our call stack. And we reached it by digging from the bottom of call stack.
How to handle java.lang.NumberFormatException ?
Use try-catch block surrounding the code that could cause NumberFormatException. Refer to the below program:
NumberFormatExceptionHandlingExample.java
/**
* @author tutorialkart.com
*/
public class NumberFormatExceptionHandlingExample {
public static void main(String[] args){
try {
int i = Integer.parseInt("25k");
System.out.println(i);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException is handled");
}
}
}
We have seen in the “How is it caused” section above, that forInputString() method returns an object of type NumberFormatException.
FYR : 65: return new NumberFormatException(“For input string: \”” + s + “\””);
This object of type java.lang.NumberFormatException contains the details collected by JVM for the cause of exception and relevant messages.
When the above above example program is run, you will get the following output.
Output
NumberFormatException is handled
Another way of handling the exception is the use of “throws” keyword. The method definition should be modified as shown in the following example.
NumberFormatExceptionHandlingExample.java
/**
* @author tutorialkart.com
*/
public class NumberFormatExceptionHandlingExample {
public static void main(String[] args){
try {
new NumberFormatExceptionHandlingExample().intParsingMethod();
} catch (NumberFormatException e) {
System.out.println("NumberFormatException is handled");
}
}
public void intParsingMethod() throws NumberFormatException{
int i = Integer.parseInt("25k");
System.out.println(i);
}
}
Output
NumberFormatException is handled
Here, method intParsingMethod() throws the exception object that is thrown by Integer.parseInt(“25k”) to its calling method, which is main() in this case.
Conclusion
In this Java Tutorial, we have learnt how to fix NumberFormatException using Java Try Catch.