NumberFormatException是 Java 中的未经检查的异常,当尝试将格式不正确的字符串转换为数值时发生。因此,当无法将字符串转换为数字类型(例如 int、float)时会引发此异常。例如,如果尝试将字符串解析为整数但字符串包含布尔值,则会发生此异常。
由于NumberFormatException是未经检查的异常,因此不需要在throws方法或构造函数的子句中声明。可以使用 try-catch 块在代码中处理它。
什么导致 NumberFormatException
可能存在与转换为数值的不正确字符串格式相关的各种情况。他们之中有一些是:
空输入字符串
Integer.parseInt(null);
空输入字符串
Integer.parseInt("");
带有前导/尾随空格的输入字符串
Integer myInt = new Integer(" 123 ");
输入带有不适当符号的字符串
Float.parseFloat("1,234");
具有非数字数据的输入字符串
Integer.parseInt("Twenty Two");
字母数字输入字符串
Integer.parseInt("Twenty 2");
输入字符串超出目标数据类型的范围
Integer.parseInt("12345678901");
输入字符串与目标数据类型之间的数据类型不匹配
Integer.parseInt("12.34");
NumberFormatException 示例
NumberFormatException 以下是尝试将字母数字字符串转换为整数时抛出的示例:
public class NumberFormatExceptionExample {
public static void main(String args[]) {
int a = Integer.parseInt("1a");
System.out.println(a);
}
}
在此示例中,尝试将包含数字和字符的字符串解析为整数,从而导致NumberFormatException:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1a"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:3)
应尽可能避免此类操作,方法是注意细节并确保尝试解析为数值的字符串是适当且合法的。
如何处理 NumberFormatException
这NumberFormatException是 Java 中的一个异常,因此可以通过以下步骤使用 try-catch 块进行处理:
NumberFormatException包围可以在 try-catch 块中抛出的语句- 赶上
NumberFormatException - 根据应用程序的要求,采取必要的措施。例如,使用适当的消息记录异常。
前面示例中的代码可以使用上述步骤进行更新:
public class NumberFormatExceptionExample {
public static void main(String args[]) {
try {
int a = Integer.parseInt("1a");
System.out.println(a);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormat Exception: invalid input string");
}
System.out.println("Continuing execution...");
}
}
像上面这样在 try-catch 块中包围代码允许程序在遇到异常后继续执行:
NumberFormat Exception: invalid input string
Continuing execution...
本文详细介绍了Java中NumberFormatException的产生原因,如空字符串、不正确的格式或超出范围的数值等,并提供了示例代码。同时,文章阐述了如何通过try-catch块来捕获和处理这种异常,确保程序在遇到问题后能够继续执行。
2660

被折叠的 条评论
为什么被折叠?



