Home >Java >javaTutorial >Why Does a Try-Catch Block with InputMismatchException Cause an Infinite Loop in Java?

Why Does a Try-Catch Block with InputMismatchException Cause an Infinite Loop in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 21:00:30306browse

Why Does a Try-Catch Block with InputMismatchException Cause an Infinite Loop in Java?

try/catch Block with InputMismatchException Causing Infinite Loop

In a Java program designed to accept integer inputs from the user, a try/catch block is used to handle invalid inputs. However, the code below encounters an infinite loop when the user enters a non-integer value, specifically InputMismatchException.

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);
    }
}

To understand why this occurs, it's crucial to examine the behavior of Scanner class when encountering an InputMismatchException. After throwing the exception, Scanner does not discard the invalid input. Instead, it remains in the input stream, potentially causing an infinite loop within the try/catch block.

The solution lies in explicitly calling input.next() within the catch block to discard the invalid token. Additionally, it's recommended to use hasNextInt() to check if a valid integer is available before accepting input.

The corrected code below follows these recommendations:

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 (InputMismatchException e) {
                System.out.println("Error!");
                input.next(); // Discard the invalid token
            }
        } while (bError);

        System.out.printf("%d/%d = %d", n1, n2, nQuotient);
    }
}

By incorporating these modifications, the try/catch block effectively handles InputMismatchException, ensuring that the program does not enter an infinite loop when the user enters invalid input.

The above is the detailed content of Why Does a Try-Catch Block with InputMismatchException Cause an Infinite Loop in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn