在try / catch中捕获exception后继续执行循环

一旦在此代码中捕获到exception,就会运行menuSystem方法,但是一旦我输入一个数字,程序就会关闭并显示“Build is successful”消息。 一旦发生exception,有没有办法重新进入while循环?

 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(); } } 

把你的try / catch放在你的while循环中

  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(); } } 

trycatch放在while循环中。 如果代码使用nextInt()则需要跳过无效输入,因为在不匹配的情况下不会使用它。

通过使用ScannerhasNextInt()方法,在尝试使用它之前输入有效输入,可以避免对InputMismatchException的exception处理:

 while (!kb.hasNextInt()) kb.next(); 

另一种方法可以做到:

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