有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java异常处理无效输入

我正在尝试Java的异常处理

我无法理解如何从文档中执行此操作,但我想做的是检测无效输入,以便在默认情况下激活开关时抛出错误。就我而言,这可能是不正确的逻辑,但我想知道是否有人能用通俗易懂的英语把我推向正确的方向

char choice = '0';
while (choice != 'q'){
     printMenu();
     System.in.read(choice);

     case '1': DisplayNumAlbums();
     case '2': ListAllTitles();
     case '3': DisplayAlbumDetail();
     case 'q': System.out.println("Invalid input...");
     return;
     default: System.out.println("Invalid input...");
     //Exception handling here
     //Incorrect input
 }            

共 (2) 个答案

  1. # 1 楼答案

    如果代码在方法中,可以声明该方法引发异常

    void method throws Exception(...){}
    

    方法的调用必须在try-catch块中

    try{
     method(...);
    }catch(SomeException e){
     //stuff to do
    }
    

    或者你可以

    while(){
     ...
     try{
      case...
      default:
       throw new IllegalArgumentException("Invalid input...");
     }catch(IllegalArgumentException iae){
      //do stuff like print stack trace or exit
      System.exit(0);
     }
    }
    
  2. # 2 楼答案

    我假设您的错误经过了仔细考虑,所以我将使用您自己的代码来制作您所要求的用法示例。因此,你仍然有责任制定一个运行程序

    异常处理机制允许您在达到某种错误条件时抛出异常,就像您的情况一样。假设您的方法名为choiceOption,您应该这样做:

    public void choiceOption() throws InvalidInputException {
        char choice = "0";
    
        while (choice != "q"){
            printMenu();
    
            System.in.read(choice);
            switch(choice){
            case "1": DisplayNumAlbums();
            case "2": ListAllTitles();
            case "3": DisplayAlbumDetail();
            case "q": System.out.println("Invalid input...");
                      return;
            default: System.out.println("Invalid input...");
                     throw new InvalidInputException();
            }
        }
    }
    

    这可以让您在客户端(任何客户端:文本、胖客户端、web等)捕获抛出的异常,并让您执行自己的客户端操作,例如,如果使用swing,则显示JOptionPane;如果使用JSF作为查看技术,则添加faces消息

    记住InvalidInputException是一个必须扩展Exception的类