NumberFormatException发生在字符串转数字失败时,如内容非数字、为空或超范围。通过try-catch捕获异常,可避免程序崩溃;转换前校验字符串是否为空、使用正则判断格式合法性,能减少异常发生;封装安全转换方法parseIntOrDefault,在异常时返回默认值,提升代码健壮性。

在Java中,NumberFormatException 是一个常见的运行时异常,通常发生在将字符串转换为数字类型(如 int、long、double 等)时,字符串内容不符合数字格式。例如使用 Integer.parseInt("abc") 就会抛出该异常。为了避免程序崩溃并提升健壮性,合理处理这一异常至关重要。
理解 NumberFormatException 的触发场景
这个异常主要出现在以下几种情况:
- 字符串为空或 null
- 包含非数字字符(如字母、符号)
- 数值超出目标类型的范围(如超过 Integer.MAX_VALUE)
- 小数点使用不当(比如用在 parseInt 中)
例如:
String str = "123abc";int num = Integer.parseInt(str); // 抛出 NumberFormatException
使用 try-catch 进行异常捕获
最直接有效的处理方式是使用 try-catch 包裹可能出错的转换代码。
立即学习“Java免费学习笔记(深入)”;
String input = "abc123";try {
int value = Integer.parseInt(input);
System.out.println("转换成功:" + value);
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是有效数字:" + input);
}
这样即使转换失败,程序也不会中断,而是进入异常处理逻辑,可以提示用户或设置默认值。
预校验字符串格式减少异常发生
在转换前对字符串进行合法性检查,能有效减少异常抛出频率,提高性能。
- 检查是否为 null 或空字符串:
if (str == null || str.trim().isEmpty()) - 使用正则表达式判断是否为纯数字:
str.matches("\\d+")(仅整数) - 对于浮点数,可使用更复杂的正则,如:
str.matches("-?\\d+(\\.\\d+)?")
示例:
public static boolean isValidInteger(String str) {if (str == null || str.trim().isEmpty()) return false;
return str.matches("-?\\d+");
}
提供默认值或安全转换工具方法
为了简化调用逻辑,可以封装一个安全转换方法,在转换失败时返回默认值。
public static int parseIntOrDefault(String str, int defaultValue) {try {
return Integer.parseInt(str.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
使用时更简洁:
int age = parseIntOrDefault(userInput, 0); 基本上就这些。关键是提前预防、合理捕获、优雅降级。不复杂但容易忽略。










