NumberFormatException常因字符串转数字失败引发,可通过try-catch捕获、预校验字符串、封装安全转换方法或使用第三方工具类如NumberUtils解决,确保程序健壮性。
在Java开发中,NumberFormatException 是一个常见的运行时异常,通常发生在尝试将不符合数字格式的字符串转换为数值类型时,比如调用
Integer.parseInt()、
Double.parseDouble()等方法。如果不妥善处理,会导致程序崩溃。下面介绍几种实用的处理技巧,帮助你更安全地进行字符串到数字的转换。
最直接的方式是通过 try-catch 包裹可能抛出异常的代码块,防止程序中断。
示例:
String str = "abc";
int num;
try {
num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("无法解析数字,使用默认值 0");
num = 0;
}
在转换前对字符串进行合法性检查,可以减少异常发生概率。
示例:判断是否为整数
public static boolean isNumeric(String str) {
if (str == null || str.isEmpty()) return false;
return str.matches("-?\\d+"); // 匹配可选负号和数字
}
// 使用
if (isNumeric(str)) {
int num = Integer.parseInt(str);
} else {
System.out.println("输入不是有效数字");
}
将解析逻辑封装成通用方法,提高代码复用性和可读性。
示例:
public static int parseInt(String str, int defaultValue) {
if (str == null || str.trim().isEmpty()) {
return defaultValue;
}
try {
return Integer.parseInt(str.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
借助第三方库简化处理流程。
示例(使用 Commons Lang):

import org.apache.commons.lang3.math.NumberUtils;
int num = NumberUtils.toInt("abc", 0); // 解析失败返回 0
基本上就这些。合理使用异常处理、前置校验和工具方法,能显著提升程序健壮性。关键是不要让 NumberFormatException 影响主流程,同时给出清晰的反馈或兜底策略。不复杂但容易忽略。