Start New Discussion within our Software Development Community

I tried to make a try-catch block in a program but when an exception occurs, it doesn't do what I intended

int num = 0;
boolean noException; 
Scanner keyboard = new Scanner(System.in); 

while (true)
        {
            noException = true; 

            System.out.print("Enter a number or 0 to exit: ");

            try
            {
                num = keyboard.nextInt(); 
            }

            catch (InputMismatchException e)
            {
                noException = false; 
                System.out.println("\nNot a valid integer");

            }

            if (noException)
            {
                //rest of program (there is a break in here to exit) 
            } 
            }

It works fine when there is no exception, but
when I enter something that gives an exception, like "1.1"
it keeps printing constantly :
*Enter a number or 0 to exit:
Not a valid integer *

It seems to be skipping the try statement, I'm not sure why.

The reason is that there's still data in the input stream after the exception has occurred.
You can fix it by reading a line when an exception occurs, using keyboard.nextLine().
Also it seems like your noException flag is redundant.

Play a bit with the following piece of code:

while (num != 0)
{
    System.out.print("Enter a number or 0 to exit: ");

    try
    {
        num = keyboard.nextInt();
        // If an exception is thrown on the line above, then all the code that
        // follows in this try block will not be executed.

        System.out.println("Input correct: " + num);

        //System.out.println("Data left in input stream = " + keyboard.nextLine());

        // Process num here
        // ...
    }
    catch (InputMismatchException e)
    {
        // Print data left in input stream
        System.out.println("\nNot a valid integer: '" + keyboard.nextLine() + "'");
    }
}
This article has been dead for over six months. Start a new discussion instead.