nfoggia
nfoggia

Reputation: 513

Java: Exception Handling not working

i have a program that I am trying to add exception handling to. The problem is, the exception that i wrote up still exits the program. Basically i offer the user to enter in any int, if they throw me a char, the exception says that they cant do that and lets them enter another int. But it isn't working giving me this 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.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at cit130_hw10_q3.Cit130_hw10_q3.main(Cit130_hw10_q3.java:29)

Java Result: 1

Here's some code. Thanks for any help you might offer.

   Scanner input = new Scanner(System.in);
   System.out.println("Enter a series of integers." +
           "When finished enter 999");
   int userInput = 0;
   int inputCount = 0;
   do{
       try{
           System.out.println("Enter an integer: ");
           userInput = input.nextInt();
           addToArray(userInput, inputCount);
       }
       catch(Exception e){
           System.out.println("Only integer values are accepted. Please try again");

       }
       inputCount++;
   }while (userInput != 999);

public static void addToArray(int nextInt , int inputCount){
    integerArray[inputCount] = nextInt;
}

Upvotes: 2

Views: 321

Answers (2)

eis
eis

Reputation: 53462

I suspect you forgot to recompile in-between or are running some other version of the code, maybe a different file than this. If you have java.lang.Exception catched like you show, this will ot happen.

Other option is that you have input.nextInt(); somewhere else, too, in a part that you did not paste here. Reconfirm line 29.

Upvotes: 2

Vineet Kasat
Vineet Kasat

Reputation: 1014

Excpetion class is the base class for all exceptions and if you are unsure of exception type you can catch it through java.lang.Excpetion and this works perfectly. In your case please put a break point in the try catch block and then confirm the point where exception is thrown. This will give an insight as why it is not getting catched at the place you mentioned

Upvotes: 0

Related Questions