0

I'm writing a Java Exception Handling program and encountered following issue.

when I enter a invalid input an infinite loop started executing instead of execution start from the try block.

public class Exception_Handling {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        boolean bl=true;
        do {

        try {
            int a = sc.nextInt();
            int b = sc.nextInt();
            bl=false;
        }
        catch(InputMismatchException ex) {
            System.out.println("Enter Valid Number Format");
            System.out.println(ex);
        }
        }while(bl);
    }   
}
1

2 Answers 2

3

You need to flush your buffer before re-entering in the loop. Otherwise java tries to read the same input again and again.

import java.util.Scanner;

public class Exception_Handling {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        boolean bl = true;
        do {

            try {
                int a = sc.nextInt();
                int b = sc.nextInt();
                bl = false;
            } catch (Exception ex) {
                System.out.println("Enter Valid Number Format");
                System.out.println(ex);
                sc.next();
            }
        } while (bl);
    }   
}

You can also use sc.reset() instead of sc.next()in your case. But if you had configured scanner with useDelimiter, useLocale or useRadix it will reset these parameters too. (see reset() java doc)

Sign up to request clarification or add additional context in comments.

Comments

0

You have a catch exception on Input Mismatch so it won't bother to execute this statement:

bl = false;

which would not terminate the loop.

public class Exception_Handling {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc=new Scanner(System.in);
    boolean bl=true;
    do {

    try {
        bl=false;
        int a = sc.nextInt();
        int b = sc.nextInt();

    }
    catch(InputMismatchException ex) {
        System.out.println("Enter Valid Number Format");
        System.out.println(ex);

    }
    }while(bl);
}   

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.