In the following SSCCE, why does the catch
block keep executing again and again, resulting in an infinite loop?
When I run this program and was prompted to enter an integer, I entered a
.
What I thought would happen was that, an InputMismatchException
would be thrown on the first line inside the try
block, and from there, the control will go to the catch
block, where it would print `` once, and then go the the next iteration of while(true)
loop, in which it should have entered the try
block again and should have prompted me to enter the integer.
But it seems to have started an unending entering into the catch block as soon as it enters the while(true)
loop, because if it was entering the try block, it would have prompted me to enter an integer again.
Where, and what, is the mistake?
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
OUTPUT
Please enter an integer:
a
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not enter an int. Please enter an integer:
You did not ...
...
...