java 为什么这个 NumberFormatException?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2193689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:58:25  来源:igfitidea点击:

Why this NumberFormatException?

java

提问by Xavier Combelle

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?

这样的堆栈跟踪是如何发生的?

回答by T.J. Crowder

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.parseLongdoesn't include the leading zero:

...它变成无效的八进制,并且 from 的异常Long.parseLong不包括前导零

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 decodecalls parseLongwithout the zero, but with the base set to 8.

它不包括它,因为decode调用parseLong没有零,但基数设置为 8。

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

谈论晦涩。:-) 因此,如果您通过显示实际输入来更新程序以处理异常,您可能会发现它与这些类似。