Search code examples
javainputmismatchexception

Java Try and Catch inputMismatchException Error


I have the following code

//Ask for weight & pass user input into the object
        System.out.printf("Enter weight: ");
        //Check make sure input is a double 
        weight = input.nextDouble();
        weight =  checkDouble(weight);
        System.out.println(weight);
        System.exit(0); 

The Method checkDouble is

Double userInput;
public static Double checkDouble(Double userInput){ 
double weights = userInput;
 try{
    }catch(InputMismatchException e){
        System.out.println("You have entered a non numeric field value");
    }
    finally {
        System.out.println("Finally!!! ;) ");
    }
    return weights;
}

When I enter a letter instead of a number i receive the following error

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at HealthProfileTest.main(HealthProfileTest.java:42)

Why won't the wrong data type input hit the System.out.println() line in the catch block?


Solution

  • As you see in stacktrace it is not thrown by your method but by nextDouble() call:

    at java.util.Scanner.nextDouble(Scanner.java:2456)
    

    And you call it here:

    weight = input.nextDouble();
    

    So you should cover this part by try catch:

    try{
    
    weight = input.nextDouble();
        }catch(InputMismatchException e){
            System.out.println("You have entered a non numeric field value");
        }
        finally {
        System.out.println("Finally!!! ;) ");
    }