java异常处理无效输入

31moq8wy  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(353)

很难说出这里要问什么。这个问题模棱两可,含糊不清,不完整,过于宽泛,或者是修辞性的,不能以现在的形式得到合理的回答。有关澄清此问题以便重新打开的帮助,请访问帮助中心。
8年前关门了。
我正在尝试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
 }
7rtdyuoh

7rtdyuoh1#

我假设您的错误已经被仔细考虑过了,所以我将使用您自己的代码来制作一个您所要求的用法示例。所以你仍然有责任运行一个程序。
异常处理机制允许您在达到某个错误条件时抛出异常,就像您的情况一样。假设您的方法被调用 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();
        }
    }
}

这可以让您在客户端(您拥有的任何客户端:text、fat client、web等)捕获抛出的异常,并让您执行自己的客户端操作,即如果您使用swing,则显示joptionpane;如果您使用jsf作为视图技术,则添加faces消息。
记得吗 InvalidInputException 是必须扩展exception的类。

btqmn9zl

btqmn9zl2#

如果你的代码在一个方法中,你可以声明这个方法抛出异常,

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);
 }
}

相关问题