用户定义的异常 Class:未报告的异常 InvalidUserInputException;必须被抓住或宣布被抛出

User Defined Exception Class: unreported exception InvalidUserInputException; must be caught or declared to be thrown

我现在正在学习如何在 Java 中创建自己的例外,并且正在查看此 tutorialspoint 页面作为参考 (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

}

我的例外情况class:

public class InvalidUserInputException extends Exception {
    private String vehicleTypes = "c/C for Car, t/T for Truck, m/M for Bus, z/Z for Zamboni, or b/B for Boat";

    public InvalidUserInputException() {

    }

    public String getValidVehicles() {
        return vehicleTypes;
    }
}

您当前逻辑的问题在于,在 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 not 被抛出。