Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try/catch with InputMismatchException creates infinite loop

Tags:

java

exception

So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code:

import java.util.InputMismatchException; import java.util.Scanner;   public class Except {     public static void main(String[] args) {         Scanner input = new Scanner(System.in);         boolean bError = true;         int n1 = 0, n2 = 0, nQuotient = 0;          do {             try {                 System.out.println("Enter first num: ");                 n1 = input.nextInt();                 System.out.println("Enter second num: ");                 n2 = input.nextInt();                 nQuotient = n1/n2;                 bError = false;             }              catch (Exception e) {                 System.out.println("Error!");             }         } while (bError);          System.out.printf("%d/%d = %d",n1,n2, nQuotient);     } } 

If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem.

like image 696
limp_chimp Avatar asked Oct 03 '12 04:10

limp_chimp


People also ask

How can we avoid InputMismatchException in Java?

To avoid the InputMismatchException , it should be ensured that the input for a Scanner object is of the correct type and is valid for the expected type. If the exception is thrown, the format of the input data should be checked and fixed for the application to execute successfully.

How do I get input mismatch exception?

There is only one simple way to avoid this exception, i.e., providing valid input(either similar type or data should be expected data type range) to the Scanner. In the above example, if we give five as input to the Scanner, the InputMismatchException will not occur.

What is the difference between NumberFormatException and InputMismatchException?

InputMismatchException is specific for the Scanner . It indicates invalid type, not necessarily an invalid number. NumberFormatException is specific for trying to convert a non numeric string to a number.

What are try and catch in Java?

Java try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.


1 Answers

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.

like image 169
Amit Deshpande Avatar answered Sep 23 '22 23:09

Amit Deshpande