在检查我的错误处理代码时偶然发现了这个。当您调用 Integer.parseInt(null)
时,Java 抛出 NumberFormatException 而 Float.parseFloat(null)
抛出 NullPointerException。另请参阅 Float 的文档和 Integer
这种差异是否有特定的技术或设计原因,或者它只是一个历史怪癖?
最佳答案
这绝对是一件历史文物。
多年来,这种不一致和相关文档问题已作为 Java Bug 多次提出。例如:
- > https://bugs.openjdk.java.net/browse/JDK-6463998
- > https://bugs.openjdk.java.net/browse/JDK-7133642
- > https://bugs.openjdk.java.net/browse/JDK-4787924
在最早的这些问题中,被指派处理该问题的 Sun 工程师写道:
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.
Will consider for Tiger. [That was Java 5.0]
2002-12-03
一年后:
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.
2003-10-21
关于java - 为什么 Float.parseFloat() 同时抛出 NumberFormatException 和 NullPointerException 而 Integer.parseInt() 只抛出 NumberFormatException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55568511/