Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this NumberFormatException?

Tags:

java

I have this stack trace (part of)

Servlet.service() for servlet action threw exception
java.lang.NumberFormatException: For input string: "37648"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
 at java.lang.Long.parseLong(Long.java:403)
 at java.lang.Long.valueOf(Long.java:482)
 at java.lang.Long.decode(Long.java:593)

in one of my logfile I don't know what was real input string. But the user had made happen the same stack trace.

How such a stacktrace can happen?

like image 454
Xavier Combelle Avatar asked Feb 03 '10 16:02

Xavier Combelle


People also ask

Why do we get NumberFormatException in Java?

The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float).

What does Java Lang NumberFormatException mean?

java.lang.NumberFormatException. Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

Which of the following statement will cause a NumberFormatException?

Common reasons for NumberFormatExceptionThere may be a mismatch between the input string and the type of the method which is being used for parsing. If you provide the input string like "1.0" and you try to convert this string into an integer value, it will throw a NumberFormatException exception.


1 Answers

Probably because they have a leading zero in their input.

This runs fine:

public class DecodeLong
{
    public static final void main(String[] params)
    {
        long    l;

        l = Long.decode("37648");
        System.out.println("l = " + l);
    }
}

But if you change this:

l = Long.decode("37648");

to this:

l = Long.decode("037648");

...it becomes invalid octal, and the exception from Long.parseLong doesn't include the leading zero:

Exception in thread "main" java.lang.NumberFormatException: For input string: "37648"
        at java.lang.NumberFormatException.forInputString(Unknown Source)
        at java.lang.Long.parseLong(Unknown Source)
        at java.lang.Long.valueOf(Unknown Source)
        at java.lang.Long.decode(Unknown Source)
        at DecodeLong.main(DecodeLong.java:24)

It doesn't include it because decode calls parseLong without the zero, but with the base set to 8.

Talk about obscure. :-) So if you update your program to handle the exception by showing the actual input, you'll probably find it's something along those lines.

like image 180
T.J. Crowder Avatar answered Oct 15 '22 04:10

T.J. Crowder