我现在正在学习如何在Java中创建自己的异常,并且正在看这个tutorialspoint页面作为参考(https://www.tutorialspoint.com/java/java_exceptions.htm),并试图使他们所做的工作尽可能地适应我的意愿。做。首先,我有一个程序可以接收用户的输入。为了确保我的用户仅输入有效的选择,当他们尝试订购无效类型的车辆时,我需要抛出异常。
当我尝试编译程序时,出现以下错误:
physics: NeverScrollableScrollPhysics(),
内部主要方法:
Orders.java:25: error: unreported exception InvalidUserInputException; must be caught or declared to be thrown
orderNewVehicle(Orders);
^
应该引发异常的orderNewVehicle方法:
try{
orderNewVehicle(Orders);
} catch (InvalidUserInputException e){
System.out.println("You've requested an invalid vehicle type. Please only enter " + e.getValidVehicles());
orderNewVehicle(Orders);
}
我的异常类:
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
}
答案 0 :(得分:0)
当前逻辑的问题在于,在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
不会抛出 。