Try/Catch With Inputmismatchexception Creates Infinite Loop

try/catch with InputMismatchException creates infinite loop

You need to call next(); when you get the error. Also it is advisable to use hasNextInt()

       catch (Exception e) {
System.out.println("Error!");
input.next();// Move to next other wise exception
}

Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that.

    Scanner scanner = new Scanner(System.in);
int n1 = 0, n2 = 0;
boolean bError = true;
while (bError) {
if (scanner.hasNextInt())
n1 = scanner.nextInt();
else {
scanner.next();
continue;
}
if (scanner.hasNextInt())
n2 = scanner.nextInt();
else {
scanner.next();
continue;
}
bError = false;
}
System.out.println(n1);
System.out.println(n2);

Javadoc of Scanner

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Java: try/catch with InputMismatchException creates infinite loop while reading of a file

You fall into infinite loop because when exception happens, the success variable didn't change its value to true. In order to do some action even when exception happens you should add the finnaly block. It could look like this:

try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}

And by the way, never do this: catch (Exception e), I did it just for example sake. Instead always catch the specific exception. Because Exception is the most basic class in the exception hierarchy, so it will catch up all the exceptions, and unless you re-throw it you could have false feeling of "safiness". When you want to catch all the exceptions, you should do this:

try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}

How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

As per the javadoc for Scanner:

When a scanner throws an
InputMismatchException, the scanner
will not pass the token that caused
the exception, so that it may be
retrieved or skipped via some other
method.

That means that if the next token is not an int, it throws the InputMismatchException, but the token stays there. So on the next iteration of the loop, reader.nextInt() reads the same token again and throws the exception again. What you need is to use it up. Add a reader.next() inside your catch to consume the token, which is invalid and needs to be discarded.

...
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
reader.next(); // this consumes the invalid token
}

how to re-try/catch input mismatch exception without getting caught by infinite loop

You're catching the wrong exception - if the input isn't an int, an InputMismatchException will be thrown. But regardless, this can be made easier by using hasNextInt():

try (Scanner scanner = new Scanner(System.in)) {
while (!scanner.hasNextInt()) {
System.err.println("Try again, this time with a proper int");
scanner.next();
}
gridSize = scanner.nextInt();
}

Try catch block causing infinite loop?

nextInt() won't discard the mismatched output; the program will try to read it over and over again, failing each time. Use the hasNextInt() method to determine whether there's an int available to be read before calling nextInt().

Make sure that when you find something in the InputStream other than an integer you clear it with nextLine() because hasNextInt() also doesn't discard input, it just tests the next token in the input stream.

try/catch infinite loop?

Use keyboard.next(); or keyboard.nextLine() in the catch clause to consume invalid token that was left from nextInt.

When InputMismatchException is thrown Scanner is not moving to next token. Instead it gives us opportunity to handle that token using different, more appropriate method like: nextLong(), nextDouble(), nextBoolean().

But if you want to move to other token you need to let scanner read it without problems. To do so use method which can accept any data, like next() or nextLine(). Without it invalid token will not be consumed and in another iteration nextInt() will again try to handle same data throwing again InputMismatchException, causing the infinite loop.

See @MarkoTopolnik answer for details about other problems in your code.

Infinite While Loop When InputMidmatchException is caught in try-catch block

No the scanner is not skipped, it's just starting at the beginning of the input. From the JavaDoc:

If the translation is successful, the scanner advances past the input that matched.

This means if the conversion isn't successfull the scanner won't advance. You'd thus have to manually skip the incorrect input using just next().

Edit: you might want to check for hasNextInt() before trying to read the input.

Question about exception (try-catch) within a loop

Probably because you did not fetch the nextInt, since the next value was not an int. thus you try to fetch the same input again in your catch block and thus have a InputMismatchException again.

Your Stacktrace also points to the catch clause where you try to retrieve the next int!

I suggest you just replace nextInt in the catch clause with nextLine:

...
catch (InputMismatchException e) {
System.out.println("Invalid Input, try again!");
scanner.nextLine();
}

Then you will start your loop again and try to read anew.

Also checkout this similar thread on stackoverflow or the tutorialspoint examples for using the Scanner class.

Catching an InputMismatchException until it is correct

Be aware that When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

To avoid "infinite loop of "Customer IDs are numbers only".", You need to call input.next(); in the catch statement to to make it possible to re-enter number in Console

From

statement

catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");

To

catch (InputMismatchException e) {
System.out.println("Customer IDs are numbers only");
input.next();
}

Example tested:

Enter Customer ID: a
Customer IDs are numbers only
b
Customer IDs are numbers only
c
Customer IDs are numbers only
11


Related Topics



Leave a reply



Submit