0

After catching an exception, how do I continue the execution of a Java program?

I made a program that asks a user to enter a number and it will return that number divided by a random number generated. However, if the user enters a letter like 'a', an exception will be caught.

How do I make the program continue its execution instead of terminating after it catches the exception?

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 
Pang
  • 9,564
  • 146
  • 81
  • 122

6 Answers6

2

Continue won't help! If you use Scanner class to input the numbers, you got an infinite loop writing "Error. You cannot divide a letter by a number!" to the output.

Your code waits for a double number, but got a letter. This event triggers an exception, the code displays the error message. But the letter will remains in the scanner, so the nextInt command tries to load the same letter in the next iteration, without wait for you typing.

In the catch block, you have to empty the scanner with a read.next() command.

    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 
1

The continue statement will restart the loop (as opposed to the break statement, which terminates the loop).

As such if you replace break; with continue;, you will keep on looping after your Exception is caught (providing no other Exception is thrown but the one caught), ans the error message is displayed.

Essentially it will print "Enter a number" again, etc.

Warning

You also need to consume the Scanner's next value. If you don't, using continue will loop forever with no user interaction when an error occurs.

Example

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

Final note

As mentioned by Berger, continue here is not even necessary because you are only printing a warning message.

Community
  • 1
  • 1
Mena
  • 47,782
  • 11
  • 87
  • 106
  • Thank you, can you elaborate on what you mean by consume the Scanner's next value? When I remove the break statement, after it catches an exception it forever prints: Enter a number, and displays the error message without giving a chance to enter. – Micheal Bingham Jan 27 '16 at 17:03
  • @MichealBingham you're welcome. See my edit: the `nextDouble` invocation will not consume the scanner's next value, only retrieve it, whereas the `nextLine` idiom will require the user to type again and return. So upon error with `nextDouble`, you'd run into an infinite loop because it keeps on failing. To fix that implies a slightly different idiom (and `Exception` handler). – Mena Jan 27 '16 at 17:05
0

The break statement is causing the end of the loop.

The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the previous discussion of the switch statement. You can also use an unlabeled break to terminate a for, while, or do-while loop

Solution :

Change it to continue.

The continue statement skips the current iteration of a for, while , or do-while loop.

Wael Sakhri
  • 397
  • 1
  • 8
0

The break statement causes the loop to exit. Since you have no code in the loop after the try-catch construct, you can simply remove the break statement.

Note that the Scanner method (I assume read is a Scanner) nextDouble() returns the double value if the next token represents a double. If not, it throws an exception without consuming that token. So you need to ensure you consume the next value, which you can do with 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); 
James_D
  • 201,275
  • 16
  • 291
  • 322
  • When I do this, the program then forever loops and asks: Enter a number, and then Displays the error message without giving the opportunity to enter a number. – Micheal Bingham Jan 27 '16 at 16:59
0

One more solution is just replace break with read.nextLine();.

break statement is causing the end of the loop.

continue will prints Enter a number again and again.

But read.nextLine();, code will asks the input again and again.

If you remove read.nextLine(); or continue, code will prints Enter a number again and again.

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
-1

Just remove the break; from there, and everything will work fine.

Remember however to put a termination condition, i don't see it anywhere.

Abhishek Anand
  • 1,940
  • 14
  • 27
  • @Mena It is sufficient. You don't need to use continue, because it a continuous loop. It will again go and ask for input. A termination condition is required only because, it is infinite loop. – Abhishek Anand Jan 27 '16 at 17:11