为何Java程序输入错误类型时未触发预期的异常捕获?
问题:Scanner输入非数值时异常处理未生效,程序直接终止
我编写了一段计算矩形面积的Java代码,使用Scanner接收用户输入。当输入实数类型的数值时程序运行正常,但输入随机字符时程序直接终止,控制台显示finished with non-zero exit value 1,并未执行catch块中的错误提示信息。疑惑为何这段代码的异常处理机制未生效?
控制台输出:
finished with non-zero exit value 1
原代码:
import java.util.Scanner; public class NewClass { public static void main(String[] args) { NewClass newClass = new NewClass(); Scanner scanner = new Scanner(System.in); try { System.out.println("Enter the first side of the rectangle: "); double firstValue = scanner.nextDouble(); System.out.println("Enter the second side of the rectangle: "); double secondValue = scanner.nextDouble(); double result = newClass.calculateRectangleArea(firstValue, secondValue); System.out.println("Area of a rectangle with sides " + firstValue + " " + "and" + secondValue + " " + "are" + result); } catch (NumberFormatException exception) { System.out.println("Please enter the correct type!"); } } public double calculateRectangleArea(double a, double b) { return a * b; } }
原因分析
你捕获的NumberFormatException并不是Scanner.nextDouble()抛出的异常类型。当输入无法解析为double类型时,nextDouble()方法会抛出**InputMismatchException**,而不是NumberFormatException。因为你没有捕获这个实际抛出的异常,它会直接向上传播,导致JVM终止程序,所以catch块的代码根本不会执行。
解决方法
- 修改捕获的异常类型:将catch块的异常改为
InputMismatchException,记得导入java.util.InputMismatchException包; - 处理错误输入残留:捕获异常后调用
scanner.next()跳过当前错误的输入内容,避免后续输入操作陷入死循环; - 优化输出语句:原输出语句的语法略有问题,调整后更通顺。
修改后的代码示例:
import java.util.Scanner; import java.util.InputMismatchException; public class NewClass { public static void main(String[] args) { NewClass newClass = new NewClass(); Scanner scanner = new Scanner(System.in); try { System.out.println("Enter the first side of the rectangle: "); double firstValue = scanner.nextDouble(); System.out.println("Enter the second side of the rectangle: "); double secondValue = scanner.nextDouble(); double result = newClass.calculateRectangleArea(firstValue, secondValue); System.out.println("Area of a rectangle with sides " + firstValue + " and " + secondValue + " is " + result); } catch (InputMismatchException exception) { System.out.println("Please enter the correct numeric type!"); // 跳过错误输入,防止后续输入操作出错 scanner.next(); } } public double calculateRectangleArea(double a, double b) { return a * b; } }
内容的提问来源于stack exchange,提问作者diho472
相关产品推荐
相关产品推荐

