【问题标题】:Continue executing loop after catching an exception in try/catch在 try/catch 中捕获异常后继续执行循环
【发布时间】:2012-12-10 16:29:07
【问题描述】:

一旦在这段代码中捕获到异常,menuSystem 方法就会运行,但是一旦我输入一个数字,程序就会关闭并显示“构建成功”消息。一旦发生异常,有什么办法可以回到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 循环中
  • 在公共论坛上寻求帮助时,请更好地格式化您的代码。
  • 如果你正确缩进你的代码,你就不需要那些多余的//end loop//end switch等cmets。
  • 编辑:尝试在循环中捕获 wasent Facepalm 感谢您的帮助

标签: java while-loop try-catch


【解决方案1】:

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

【讨论】:

  • 我今天学到了一些新东西。谢谢。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    另一种方法:

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

    【讨论】:

    • 我知道这是一个较老的问题,但您能否详细说明 continue 在这种情况下应该做什么?
    • 抱歉,暗示继续。无论如何它都会继续循环。
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2019-02-21
    • 2020-07-01
    • 2011-02-07
    • 2022-01-26
    • 2012-06-04
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多