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

668 Views Asked by At

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


  }
}```
3

There are 3 best solutions below

0
On BEST ANSWER

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();
    }
0
On

The reason is that you are catching the error in the catch block. Try to implement a loop for it. Also remember to clear the buffer using input.next(); otherwise you will encounter infinite-loop

do
{
    try
    {
        System.out.printf("Hey, %s. How old are you?: ", name);
        age = input.nextInt();
        stop = true;
    } 
    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.next(); // Clearing the buffer. This is important otherwise Infinite Loop will occur
    }
} while( !stop );
0
On

You need an additional try-catch around

height_in_cm = input.nextInt();

Or else you'll get another exception!