创建短号码时出现 NumberFormatException

Posted

技术标签:

【中文标题】创建短号码时出现 NumberFormatException【英文标题】:NumberFormatException when create Short number 【发布时间】:2018-05-09 07:21:33 【问题描述】:

我在以下代码中遇到 NumberFormatException 期间正在处理包装类,请告诉我为什么在此运行时异常之前我们没有遇到编译时错误,为什么只有运行时 NumberFormat 异常没有编译时错误。

Short s3 = new Short("32770");
System.out.println(s3);

例外

线程“main”java.lang.NumberFormatException 中的异常:值超出范围。值:"32770" 基数:10

【问题讨论】:

评估是在运行时完成的,而不是在编译时 【参考方案1】:

见tutorial:

Short范围从 -32,76832,767 在 java 中。 32770 不是有效的 short

【讨论】:

@iramkahkashan 不要感谢您的回复,而是赞成并接受答案。【参考方案2】:

只有在以下情况下才会出现异常:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

    The first argument is null or is a string of length zero.
    The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
    Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.
    The value represented by the string is not a value of type short.

【讨论】:

【参考方案3】:

如前所述,范围是从-32768到32767。您将 "32770" 作为值传递给超出范围的 Short 构造函数。

您不会收到任何编译时错误,因为您将有效类型的参数传递给构造函数。 该值在运行时发生的实际执行期间进行验证,因此 NumberFormatException 而不是任何编译错误

【讨论】:

感谢您的回复。

以上是关于创建短号码时出现 NumberFormatException的主要内容,如果未能解决你的问题,请参考以下文章