Skip to main content

Looping "try/catch" help

Please note these forums are being decommissioned and use the new and improved forums at
2 replies [Last post]
Joined: 2012-04-21

When I run the below method and intentionally input a letter when a number is expected, I get a never-ending loop that doesn't prompt for more input. Why?

private static int intInput() //Asks the user for an int and returns the input.
Scanner genericIntScan = new Scanner(;
    boolean itsAnInt = false;
    int genericInt = 0;
      genericInt = genericIntScan.nextInt();
      itsAnInt = true;
    catch(InputMismatchException ime)
      System.out.println("\nYou're supposed to type in a number. Try again.");
      itsAnInt = false;
   return genericInt;

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2006-02-17

have you tried adding a print statement inside the try block to see how far down that block the code is going. sounds like it is going into that block and never coming out. if it is coming out of the try block into the catch block then you are setting itsAnInt to false which is causing the loop to complete again. another thing i would catch is to make sure you are catching the error type you think you are catching. if a different type of error it getting thrown then that might be causing problems. that's three things you might look into further.

Joined: 2012-05-14

Thanks for the answer.