NumberFormatException是运行时异常,由字符串转数字方法如Integer.parseInt()或Double.parseDouble()在格式错误时抛出。

在Java中,NumberFormatException 是运行时异常,通常发生在将字符串转换为数字类型(如 Integer.parseInt()、Double.parseDouble()) 等)但字符串格式不合法时。为了避免程序崩溃,并提升健壮性,我们可以通过捕获该异常并返回一个默认值来实现“回退”处理。
以下代码会抛出 NumberFormatException:
String input = "abc"; int value = Integer.parseInt(input); // 抛出异常当输入无法解析为有效数字时,直接调用 parse 方法就会失败。为了安全处理,应使用 try-catch 结构。
最直接的方式是捕获异常并在 catch 块中返回预设的默认值:
立即学习“Java免费学习笔记(深入)”;
public static int parseIntWithDefault(String str, int defaultValue) { try { return Integer.parseInt(str.trim()); } catch (NumberFormatException e) { return defaultValue; } }示例调用:
System.out.println(parseIntWithDefault("123", 0)); // 输出 123 System.out.println(parseIntWithDefault("xyz", -1)); // 输出 -1 System.out.println(parseIntWithDefault("", 0)); // 输出 0(空字符串也会异常)可以扩展为支持多种类型,提高复用性:
public class NumberUtils { public static int parseInt(String str, int defaultValue) { if (str == null || str.isEmpty()) return defaultValue; try { return Integer.parseInt(str.trim()); } catch (NumberFormatException e) { return defaultValue; } } public static double parseDouble(String str, double defaultValue) { if (str == null || str.isEmpty()) return defaultValue; try { return Double.parseDouble(str.trim()); } catch (NumberFormatException e) { return defaultValue; } } // 其他类型类似... }这样在多个地方需要解析数字时,可以直接调用工具类,逻辑统一且易于维护。
若频繁处理非数字字符串,可在解析前先判断格式是否合法,减少异常开销:
public static int parseIntWithPattern(String str, int defaultValue) { if (str == null || str.trim().isEmpty()) return defaultValue; str = str.trim(); // 匹配整数(含负数) if (str.matches("-?\d+")) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return defaultValue; } } else { return defaultValue; } }注意:正则判断虽能减少异常触发,但也增加了额外检查成本,需根据实际场景权衡。
基本上就这些。通过 try-catch 捕获 NumberFormatException 并返回默认值,是 Java 中安全解析字符串数字的标准做法。配合空值检查和工具类封装,可以让代码更简洁、健壮。不复杂但容易忽略细节,比如 trim 和 null 判断。
以上就是Java里如何处理NumberFormatException并回退默认值_数字格式异常回退处理解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号