Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue executing loop after catching an exception in try/catch

Once an exception is caught in this code, the menuSystem method is run, but once I go to input a number the programme closes and the "Build is successful" message is displayed. Is there any way to get back into the while loop once an exception has occured?

public static void main(String[] args) {
   final UnitResults myUnit = new UnitResults(10, "Java");
   int option = menuSystem();

   try {
      while (option != 0) {
         final Scanner keyb = new Scanner(System.in);
         System.out.println("");
         switch (option) {
         }
      }
   } catch (Exception InputMismachException) {
      System.out.println("\nPlease Enter a Valid Number\n");
      option = menuSystem();
   }
}
like image 851
Bunion Avatar asked Dec 10 '12 16:12

Bunion


2 Answers

put your try/catch inside your while loop:

    while (option != 0) {
        final Scanner keyb = new Scanner(System.in);
        System.out.println("");
        try {
            switch (option) {

            }
        } catch (Exception InputMismachException) {
            System.out.println("\nPlease Enter a Valid Number\n");
            option = menuSystem();
        }
    }
like image 61
PermGenError Avatar answered Nov 18 '22 19:11

PermGenError


Put the try and catch within the while loop. If the code is using nextInt() then you need to skip the invalid input as it will not be consumed in the event of a mismatch.

It would be possible to avoid the exception handling for InputMismatchException by using the hasNextInt() methods of Scanner until a valid input is entered before attempting to consume it:

while (!kb.hasNextInt()) kb.next();
like image 25
hmjd Avatar answered Nov 18 '22 18:11

hmjd