Search code examples
javavalidationtry-catch

InputMismatch Avoidance with try-catch


To validate for an int input, I've seen the usage of try-catch using the InputMismatch exception. After inputting a string though, I simply get the catch code block played, then my program exits due to mismatch, but instead I want to allow the user to re-enter input. I implemented a boolean correct while loop after searching around but that still didn't do the trick.

        int quantity = 0;
        boolean correct = true;
        while(correct){
            try{
                System.out.print("Input Quantity you would like to purchase: ");//Get quantity
                quantity = input.nextInt();
            }catch(InputMismatchException e){
                System.out.println("Input must be a number");
                input.nextInt();//Get the input as a string
                correct = false;
            }
            System.out.println("Quantity: " + quantity);
        }

I previously just used the Scanner's built in hasNextInt, and that works great, but wanted to test out try-catch. I've heard to use try-catch and not to use try-catch. Why would I avoid using it?


Solution

  • Here is the fix, use input.nextLine(); in catch and don't make the correct=false

    while(correct){
                try{
                    System.out.print("Input Quantity you would like to purchase: ");//Get quantity
                    quantity = input.nextInt();
                }catch(InputMismatchException e){
                    System.out.println("Input must be a number");
                    input.nextLine();
                    continue;
                }
                System.out.println("Quantity: " + quantity);
            }
    

    But like others pointed out, try not to use Exceptions for general flow. Use it only for tracking unusual exceptions. So, I am discouraging you to use this code. Use, input.hasNextInt() instead