NumberFormatException出现在字符串无法解析为数字时,如Integer.parseInt("abc")会抛出该异常;通过try-catch捕获异常并结合trim()、判空和正则校验等手段可有效防止程序崩溃,提升健壮性。

在Java中,NumberFormatException 是一个运行时异常,通常发生在尝试将不符合数字格式的字符串转换为数值类型时,比如使用 Integer.parseInt()、Double.parseDouble() 等方法。为了防止程序因无效输入而崩溃,应当通过 try-catch 块来捕获并处理该异常。
当你执行如下代码:
String str = "abc"; int num = Integer.parseInt(str); // 抛出 NumberFormatException
因为字符串 "abc" 无法解析为整数,JVM 会抛出 NumberFormatException。如果不处理,程序将中断执行。
使用 try-catch 结构可以安全地进行字符串到数字的转换:
立即学习“Java免费学习笔记(深入)”;
String input = "123abc";
try {
int value = Integer.parseInt(input);
System.out.println("解析结果:" + value);
} catch (NumberFormatException e) {
System.err.println("输入的字符串不是有效的数字格式:\"" + input + "\"");
}
这样即使输入非法,程序也不会崩溃,而是输出错误提示信息。
在实际开发中,可以结合判断逻辑提升容错能力:
trim() 去除首尾空格,避免 " 123 " 这类误判
String input = " 456 ";
int result = 0;
if (input != null && !input.trim().isEmpty()) {
try {
result = Integer.parseInt(input.trim());
} catch (NumberFormatException e) {
System.out.println("无法解析数字,使用默认值0");
}
} else {
System.out.println("输入为空,使用默认值0");
}
System.out.println("最终数值:" + result);
基本上就这些。合理使用 try-catch,配合输入校验,能有效避免 NumberFormatException 导致的程序异常退出。
以上就是在Java中如何捕获并处理NumberFormatException的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号