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() + "'");
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.