Java 为什么 Double.parseDouble(null) 和 Integer.parseInt(null) 会抛出不同的异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16324831/
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-08-16 06:18:46  来源:igfitidea点击:

Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions?

javaexceptionnullpointerexceptionnumberformatexception

提问by pho79

Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions?

为什么 Double.parseDouble(null) 和 Integer.parseInt(null) 会抛出不同的异常?

Is this a historical accident or intentional? The documentation clearly states two types of exceptions for Double.parseDouble(...)and one for Integer.parseInt(), but it seems inconsistent:

这是历史意外还是有意为之?该文档清楚地说明了两种类型的异常 forDouble.parseDouble(...)和一种 for Integer.parseInt(),但似乎不一致:

Integer.parseInt(null); // throws java.lang.NumberFormatException: null

However

然而

Double.parseDouble(null); // throws java.lang.NullPointerException

采纳答案by Floris Velleman

It is reasonable to expect the same exceptions to be thrown for null; however, these api's are very old and may not be able to be changed at this point.

期望为 null 抛出相同的异常是合理的;但是,这些 api 非常旧,此时可能无法更改。

And:

和:

Since the exception behavior is long-standing and specified in the JavaDoc, it is impractical to change either method's behavior at this time. Closing as will not fix.

由于异常行为长期存在并在 JavaDoc 中指定,因此此时更改任一方法的行为是不切实际的。关闭不会修复。

As taken from: Bug Report: Integer.parseInt() and Double.parseDouble() throw different exceptions on null.

摘自:错误报告:Integer.parseInt() 和 Double.parseDouble() 在 null 上抛出不同的异常。

Like others have stated: It's likely made by different authors.

就像其他人所说的那样:它可能是由不同的作者制作的。

回答by durron597

Note: everything in this post is in the source of Java7-b147

注:本文所有内容均在Java7-b147源码中

Double.parseDouble()goes into a Sun library (in sun.misc.FloatingDecimal) the first important thing that happens is:

Double.parseDouble()进入 Sun 图书馆(在sun.misc.FloatingDecimal),发生的第一件重要事情是:

in = in.trim(); // don't fool around with white space.
                // throws NullPointerException if null

Integer.parseInt()is done manually in the Integerclass. The first important thing that happens is:

Integer.parseInt()Integer课堂上手动完成。发生的第一件重要的事情是:

if (s == null) {
    throw new NumberFormatException("null");
}

I would guess there are two different authors.

我猜有两个不同的作者。