0

I can't figure out why my getHours() is catching InputMismatchException when I have only thrown InvalidHrExcep to the method itself. Can anyone enlighten me?

public static void main (String [] args)
{
    do
    {
        try
        {
            getHours();
            getAmPm();
            accept = true;
        }
        catch(InvalidHrExcep h)
        {
            System.out.println (h);
            accept = false;
            console.nextLine();
        }
        catch (InputMismatchException e)
        {
            System.out.println (e);
            System.out.println("Input must be AM or PM.");
            accept = false;
            console.nextLine();
        }
    }while(accept == false);
}

My method for getHours()

public static int getHours() throws InvalidHrExcep
{
    System.out.print ("Enter hours: ");
    int hour = console.nextInt();

    if(hour > 0 && hour <= 12)
    {
        return hour;
    }
    else
    {
        throw new InvalidHrExcep();
    }
}
Zac Ee
  • 31
  • 5
  • 1
    your getHours isn't catching anything. it might throw it, which is a different matter. I would recommend adding e.printStackTrace(); into your catch block, going through the stacktrace 'll make it easier to see where the exception is thrown. so far, there is no reason to believe it was thrown by getHours() – Stultuske Nov 13 '18 at 08:10
  • 2
    We have no idea what `getHours()` does. – Eran Nov 13 '18 at 08:11
  • Oops, ok I have added my getHours() method. – Zac Ee Nov 13 '18 at 08:14
  • can you show the implementation of InvalidHrExcep if it is a Exception you have implemented? – Sandeepa Nov 13 '18 at 08:16
  • what did you provide as input for the getHours() method? nextInt might throw that exception, if the input you've entered is not a valid int – Stultuske Nov 13 '18 at 08:16
  • @Sand it's quite unlikely for the constructor of one Exception type to throw a completely different one – Stultuske Nov 13 '18 at 08:18
  • Ok oops guys i realised that I only specify my condition to be a range of numbers. MY BAD! I kept testing using characters. – Zac Ee Nov 13 '18 at 08:30

1 Answers1

0

console.nextInt() can definitely throw InputMismatchException exception, and your getHours method doesn't have to specify that exception in a throws clause, since it's an unchecked exception.

If you don't want getHours() to throw that exception, you should put console.nextInt() in a try block and catch it.

Eran
  • 387,369
  • 54
  • 702
  • 768