繁体   English   中英

捕获异常后继续执行程序

[英]Continue Program Execution after Catching Exception

捕获异常后,如何继续执行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块中,您必须使用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 

continue语句将重新启动循环(与break语句相对,后者将终止循环)。

因此,如果您替换break; continue; ,您将在捕获到您的Exception后继续循环播放(假设没有其他Exception抛出,而是捕获了一个Exception ),并且显示错误消息。

本质上,它将再次打印"Enter a number" ,依此类推。

警告

您还需要消耗Scanner的下一个值。 如果不这样做,则在发生错误时,使用continue将永远循环,而无需用户干预。

Scanner read = new Scanner(System.in);
do {
    try {
        // trimmed out non-necessary stuff
        System.out.println("Enter a number");
        double i = Double.parseDouble(read.nextLine());
        System.out.println(i);
        // changed exception caught
    } 
    catch (NumberFormatException type_error) {
        System.out.println("Error. You cannot divide a letter by a number!");
        continue;
    }

} while (true);

最后说明

Berger所述 ,即使您仅打印警告消息,也不必continue此处。

break语句导致循环结束。

break语句有两种形式:带标签的和不带标签的。 您在前面对switch语句的讨论中看到了未标记的形式。 您还可以使用无标签的中断来终止 for,while或do-while循环

解决方案:

更改它以continue

continue语句跳过的当前迭代,while或do-while循环。

break语句导致循环退出。 try - catch构造之后,由于循环中没有代码,因此只需删除break语句即可。

请注意,如果下一个标记表示一个double值,则Scanner方法(假设readScannernextDouble()返回double值。 如果不是,它将抛出一个异常而不消耗该令牌。 因此,您需要确保使用下一个值,您可以使用read.next()

do{                     //Begin 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 " + read.next() + " by a number!"); 

    } 



} while(true); 

read.nextLine();一种解决方案是将break替换为read.nextLine();

break语句导致循环结束。

continue将打印再次Enter a number

但是read.nextLine(); ,代码将一次又一次地询问输入。

如果删除read.nextLine(); continue ,代码将打印一次又一次输入数字。

删除中断即可; 从那里开始,一切都会正常。

但是请记住,要设置终止条件,我在任何地方都看不到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM