Xavier Combelle
Xavier Combelle

Reputation: 11235

Why this NumberFormatException?

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?

Upvotes: 13

Views: 15824

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075765

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.

Upvotes: 34

Related Questions