Continue loop after detecting exception in try / catch

As soon as an exception falls into this code, the menuSystem method menuSystem , but as soon as I go to enter the number, the program closes and the message "Build is successful" is displayed. Is there a way to return to the while loop after an exception occurs?

 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(); } } 
+7
source share
3 answers

put try / catch inside the 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(); } } 
+15
source

Put try and catch in a while . If the code uses nextInt() , you need to skip invalid input as it will not be used in case of a mismatch.

It would be possible to avoid handling exceptions for InputMismatchException using the hasNextInt() Scanner methods until the correct input is entered before trying to use it:

 while (!kb.hasNextInt()) kb.next(); 
+1
source

Another way you can do this:

  List<File> directories; ... for ( File f : directories ) { try { processFolder(f); } catch( Exception e ) { SimpleLog.write(e); } } 
0
source

All Articles