java - 为什么 Float.parseFloat() 同时抛出 NumberFormatException 和 NullPointerException 而 Integer.parseInt() 只抛出 NumberFormatException?

标签 java exception

在检查我的错误处理代码时偶然发现了这个。当您调用 Integer.parseInt(null) 时,Java 抛出 NumberFormatException 而 Float.parseFloat(null) 抛出 NullPointerException。另请参阅 Float 的文档和 Integer

这种差异是否有特定的技术或设计原因,或者它只是一个历史怪癖?

最佳答案

这绝对是一件历史文物。

多年来,这种不一致和相关文档问题已作为 Java Bug 多次提出。例如:

在最早的这些问题中,被指派处理该问题的 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/

相关文章:

java - Java相当于Kotlin的Function0和Function1吗?

java - 无法在套接字列表循环中获取套接字的 DataOutputStream

Python - 未引发异常

java - 尝试 parseDouble 时发现异常

php - Artisan 命令的自定义错误和异常处理程序

java - 不同的随机数

java - Android proguard 忽略除一个类之外的所有类

Java 32 位 JRE : can this JRE run a 64 bit program?

MySQL JDBC语法错误异常

c# - 异常处理循环拼图