java - 捕获异常后继续执行程序

标签 java exception try-catch inputmismatchexception

捕获异常后,如何继续执行Java程序?

我编写了一个程序,要求用户输入一个数字,它将返回该数字除以生成的随机数。但是,如果用户输入像“a”这样的字母,则会捕获异常。

如何让程序在捕获异常后继续执行而不是终止?

do{                     //Begin of loop 
    try{                        //Try this code 
        System.out.println("Enter a number"); 
        double i = read.nextDouble(); //Reads user input  
        double rn = r.nextInt(10);   //Generates random number rn 
        System.out.println(i +  " divided by random number " + rn + " is " + (i/rn)); 
    }catch(InputMismatchException type_error){         //Catches error if there is a type mismatch
        //Example error: if user enters a letter instead of a double
         System.out.println("Error. You cannot divide a letter by a number!"); 
        break;  //break stops the execution of the program 
    } 

    //using a continue statement here does not work 
}while(true);       //Loop forever 

最佳答案

继续没有帮助!如果您使用 Scanner 类输入数字,则会出现无限循环,写入“错误。您不能将字母除以数字!”到输出。

您的代码等待双数,但收到一封信。该事件触发异常,代码显示错误消息。但该字母将保留在扫描仪中,因此 nextInt 命令会尝试在下一次迭代中加载相同的字母,而无需等待您输入。

在 catch block 中,您必须使用 read.next() 命令清空扫描器。

    Scanner read = new Scanner(System.in);
    Random r = new Random();

    do {                     //Begin of loop 

        try {                        //Try this code 
            System.out.println("Enter a number");
            double i = read.nextDouble(); //Reads user input  
            double rn = r.nextInt(10);   //Generates random number rn 
            System.out.println(i + " divided by random number " + rn + " is " + (i / rn));

        } catch (InputMismatchException type_error) {         //Catches error if there is a type mismatch
            //Example error: if user enters a letter instead of a double
            System.out.println("Error. You cannot divide a letter by a number!");

            // Empty the scanner before the next iteration: 
            read.next();
        }

    //using a continue statement here does not work 
    } while (true);       //Loop forever 

关于java - 捕获异常后继续执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043340/

相关文章:

Java - 循环多个数组(字符串与 "array type"不匹配)

java - Vaadin 实用程序记录器异常

python - 当切片索引超出范围时如何引发 IndexError?

ios - 从 (_,_,_) 类型的抛出函数 throws -> Void 到非抛出函数类型 (NSData?, NSURLResponse?, NSError?) -> Void 的无效转换

node.js - 无法发现错误? : NodeJS/Hyperledger

java - 我的 try catch 循环陷入无限循环,每次都应该提示用户输入

java - 不稳定的 StampedLock.unlock(long) 行为?

java - Playframework 中的 ConcurrentModificationException

c# - 委托(delegate) - 异常不会等到调用 EndInvoke()

java - 如何获取给定文本中 N 个最常用的单词,从最大到最小排序?