Search code examples
javaexceptioninputmismatchexception

Catch isn't catching InputMismatchException?


So, I've searched around google and stackoverflow for a bit, but I can't seem to find an answer to this issue.

I've got 2 methods. The first method, getAge is meant to just get an integer as input from the user. It's then meant to pass that input to verifyAge, who makes sure it's in the right range.

However; if they should enter anything that is not an integer, it's supposed to display a message and call getAge again, to restart the input process. I have a try-catch set up, but it still goes back to JVM. According to an answer in another post; what I'm doing is correct. But it still doesn't seem to be working. So here's the errors I get when I try to run it as I have it now:

Please enter your age: notint
Exception in thread "main" java.util.InputMismatchException
 at java.util.Scanner.throwFor(Scanner.java:864)
 at java.util.Scanner.next(Scanner.java:1485)
 at java.util.Scanner.nextInt(Scanner.java:2117)
 at java.util.Scanner.nextInt(Scanner.java:2076)
 at Ch2ProgLabWilson.getAge(Ch2ProgLabWilson.java:22)
 at Ch2ProgLabWilson.main(Ch2ProgLabWilson.java:15)

What I have written:

import java.util.* ;
import java.util.Scanner;

public class Ch2ProgLabWilson {

 public static void main(String[] args) {

      getAge();  
 }

 public static int getAge()
 {
  Scanner keyboard = new Scanner(System.in);
  System.out.print("Please enter your age: ");
  int a = keyboard.nextInt();
  verifyAge(a);

     try
     {
        getAge();
     }    
     catch (InputMismatchException e)
        {
           System.out.println("You may only enter integers as an age. Try again.");
           getAge();
        }

    return a;
   }

 // 
 public static boolean verifyAge (int a)
     {
        if (a >= 0 && a <= 122)
        {
           System.out.println("The age you entered, " + a + ", is valid.");
           return true;
        }
        else
        {
           System.out.println("The age must be from 0 to 122, cannot be negative, and has to be an integer.");
           getAge();
           return false;
        }   
     }

 }

Solution

  • Look at the line of code which actually throws the Exception. If it is not in the try/catch block, it will not be caught.

    Try this instead:

    try
    {
        int a = keyboard.nextInt();
        verifyAge(a);
    }    
    catch (InputMismatchException e)
    {
        System.out.println("You may only enter integers as an age. Try again.");
        getAge();
    }