0

The code -

for(int i = 0; i < count; i++)
    {
     System.out.println("Please enter a number!");
    try{
         numbers[i] = keyboardScanner.nextInt();
    }catch(InputMismatchException ex)
    {
      System.out.println("You did not enter a number!");
    }
}

If you enter a String, it loops till 'count'. Why does that happen ?

0

1 Answer 1

4

Sure, it'll loop until count: you caught the exception and continued the loop anyway.

You want to break out of your loop when you get that exception:

System.out.println("You did not enter a number!");
break;
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, the break will help. But, i have another question. Why not design the Java language such that the loop will not execute fully if some exception is thrown ?
@Apple Grinder: Because there might be good reasons to stay in the loop after an exception was thrown.
It is because the exception is caught, period. Caught exceptions are not thrown from try-catch!!!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.