Micheal Bingham
Micheal Bingham

Reputation: 19

Continue Program Execution after Catching Exception

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 

Upvotes: 0

Views: 7948

Answers (6)

SatyaTNV
SatyaTNV

Reputation: 4135

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.

Upvotes: 0

András Gazdag
András Gazdag

Reputation: 21

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 

Upvotes: 2

James_D
James_D

Reputation: 209714

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

Upvotes: 0

Abhishek Anand
Abhishek Anand

Reputation: 1992

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

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

Upvotes: -1

Mena
Mena

Reputation: 48444

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.

Upvotes: 1

Wael Sakhri
Wael Sakhri

Reputation: 397

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.

Upvotes: 0

Related Questions