我现在正在学习如何在 Java 中创建自己的例外,并正在查看本教程点页面作为参考(https://www.tutorialspoint.com/java/java_exceptions.htm)并尝试适应他们所做的最好我可以做我想做的事。首先,我有一个接收用户输入的程序。为了确保我的用户只输入有效的选择,当他们尝试订购无效类型的车辆时,我需要抛出异常。当我尝试编译我的程序时,出现以下错误:Orders.java:25: error: unreported exception InvalidUserInputException; must be caught or declared to be thrown orderNewVehicle(Orders); ^内部主要方法:try{ orderNewVehicle(Orders);} catch (InvalidUserInputException e){ System.out.println("You've requested an invalid vehicle type. Please only enter " + e.getValidVehicles()); orderNewVehicle(Orders);}应该抛出我的异常的 orderNewVehicle 方法:public static void orderNewVehicle(ArrayList listOfOrders) throws InvalidUserInputException{ String vehicleType = ""; System.out.print("Do you want to order a Truck (T/t), Car (C/c), Bus(M/m), Zamboni(Z/z), or Boat(B/b)? "); Boolean validVehicle = false; while(validVehicle.equals(false)) { Scanner scan = new Scanner(System.in); String potentialInput = scan.next(); if(!(potentialInput.equals("c") || potentialInput.equals("C") || potentialInput.equals("t") || potentialInput.equals("T") || potentialInput.equals("b") || potentialInput.equals("B") || potentialInput.equals("m") || potentialInput.equals("M") || potentialInput.equals("z") || potentialInput.equals("Z"))) { // System.out.print("Invalid input. Only enter c/C for Car, t/T for Truck, m/M for Bus, z/Z for Zamboni, or b/B for Boat. Please Try Again: "); scan.nextLine(); //Clear carriage return if one present throw new InvalidUserInputException(); } else { validVehicle = true; vehicleType = potentialInput; scan.nextLine(); } } System.out.println(""); // stuff that happens once we get past the input check}
1 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
您当前逻辑的问题在于,在catch块中您再次调用可能引发异常的方法。编译器只是告诉您,您还必须捕获其他异常。
为了立即解决您的问题,您可以尝试以下方法:
final String msg = "You've requested an invalid vehicle type. Please only enter ";
boolean success = false;
do {
try {
orderNewVehicle(Orders);
success = true;
}
catch (InvalidUserInputException e){
System.out.println(msg + e.getValidVehicles());
}
} while (!success);
在上面的版本中,我们循环调用orderNewVehicle, 直到成功调用。我们知道,一个呼叫已经成功,如果success标志可以被设置为true,这将意味着一个InvalidUserInputException已不被抛出。
添加回答
举报
0/150
提交
取消