您的位置:首页 >Java中Scanner输入类型错误未捕获异常的原因及解决方法
发布于2026-03-05 阅读(0)
扫一扫,手机访问

当使用Scanner的nextDouble()等方法读取非匹配类型输入时,会抛出InputMismatchException而非NumberFormatException,若catch块未正确声明该异常类型,则异常将未被捕获而直接终止程序。
在Java中,Scanner类提供了便捷的类型化输入方法(如nextDouble()、nextInt()、nextBoolean()等),但其异常处理机制常被初学者误解。关键点在于:这些方法在输入不匹配时抛出的是 InputMismatchException(运行时异常,继承自RuntimeException),而非NumberFormatException。
例如,以下代码看似合理,实则存在根本性异常捕获错误:
import java.util.Scanner;
import java.util.InputMismatchException; // 注意:需显式导入!
public class RectangleAreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the first side of the rectangle: ");
double firstValue = scanner.nextDouble(); // ← 输入 "abc" 时抛出 InputMismatchException
System.out.print("Enter the second side of the rectangle: ");
double secondValue = scanner.nextDouble();
double area = calculateRectangleArea(firstValue, secondValue);
System.out.printf("Area of rectangle with sides %.2f and %.2f is %.2f%n",
firstValue, secondValue, area);
} catch (InputMismatchException e) { // ✅ 正确捕获
System.err.println("Error: Please enter a valid number (e.g., 3.14 or 5).");
} finally {
scanner.close(); // 始终关闭资源,避免内存泄漏
}
}
public static double calculateRectangleArea(double a, double b) {
return a * b;
}
}⚠️ 重要注意事项:
} catch (InputMismatchException e) {
System.err.println("Invalid input — please enter a numeric value.");
scanner.next(); // ← 清除错误输入,避免死循环
}✅ 最佳实践总结:
掌握这一区别,是编写稳定、用户体验良好的控制台交互程序的关键基础。
上一篇:米侠浏览器显示异常修复方法
下一篇:机械硬盘咔哒声预警:是否快坏了?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9