javaexceptioninputmismatchexception

The Program still throws an InputMismatchException and exits even though its been caught


I am just learning Java and I'm struggling with Exception handling. I am trying to write a quick program that takes some inputs and exports them converted into different units.

I am using Scanner to take the input and I'm trying to protect against an InputMisatchException but despite putting a try-catch block around it to handle the exception it still exits. the code is bellow. Hope you can help! Thanks in advance.

import java.util.InputMismatchException;

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    //init variables
    String name = "";
    int age = -1;
    int height_in_cm = -1;

    //Init Scanner
    Scanner input = new Scanner(System.in);

    //Get the input from the user and save to the initiated variables above.
    System.out.print("Please enter your name: ");
    name = input.nextLine();
    try{
    System.out.printf("Hey, %s. How old are you?: ", name);
    age = input.nextInt();
    } catch (InputMismatchException e){
        System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ", name);
        age = input.nextInt();
    }
    System.out.print("And finally, what is your height in CM?: ");
    height_in_cm = input.nextInt();

    //close the scanner to protect from resource leaks.
    input.close();


  }
}```

Solution

  • The reason for the exception is that when the exception is thrown for the first time the Scanner (input) does not update its pointer, so the input.nextInt() in the catch block reads the same input as the input.nextInt() of the try block.

    To resolve this, add input.nextLine() in the catch block before reading the int value.

     try{
            System.out.printf("Hey, %s. How old are you?: ", name);
            age = input.nextInt();
        } catch (InputMismatchException e){
            System.out.printf("Agh! Sorry %s. We were expecting a number made up of digits between 0-9. Try again for us? \n How old are you?: ", name);
            input.nextLine();
            age = input.nextInt();
        }