我现在正在学习如何在 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
}
宝慕林4294392
相关分类