2012-12-10 113 views
7

一旦在此代码中发现异常,将运行menuSystem方法,但是一旦我输入一个数字,程序就会关闭并显示“Build is successful”消息。一旦发生异常,有什么办法可以回到while循环?在try/catch中捕获异常后继续执行循环

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

您想将try/catch放在while循环中 – antlersoft

+1

请在公共论坛上寻求帮助时更好地格式化您的代码。 – Perception

+0

如果你正确地缩进你的代码,你将不需要那些冗余的'// end loop','// end switch'等注释。 –

回答

15

把你的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(); 
     } 
    } 
1

trycatchwhile循环中。如果代码使用nextInt(),那么您需要跳过无效输入,因为在不匹配的情况下它不会被使用。

这将有可能避免的异常使用的ScannerhasNextInt()方法,直到一个有效的输入处理为InputMismatchException试图在消费之前输入:

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

另一种方式,你可以做到这一点:

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

我知道这是一个较老的问题,但你能详细说明在这种情况下'继续'应该做什么? – Nils

+0

对不起,继续暗示。无论如何,它将持续循环。 – djangofan