2016-02-24 38 views
1

我需要在java内部循环中处理自定义异常,所以我抛出新的自定义异常但它打破了循环。我们如何设法在不断开循环的情况下抛出循环。这里是我的代码在java中抛出异常而不断开循环

for (int i = 0; i < j; i++) { 
     File currFile = arrayOfFile1[i]; 
     if (currFile.isFile()) { 
      if (currFile.exists()) { 
       try { 
        String fileName = currFile.getName(); 
        if (fileName.startsWith("~$")) { 
         continue; 
        } else { 
         if ((fileName.endsWith(".xlsx")) || (fileName.endsWith(".xls"))) { 
          if (fileName.endsWith("_arch.xlsx") || fileName.endsWith("_arch.xls")) { 
           continue; 
          } 
          try { 
           IDSOutputGenerator.generateOutput(currFile.getAbsolutePath(), "", outputType, 
             false); 
          } catch (CheckErrorHandle e) { 
           throw new CheckErrorHandle(); 
          } 
         } 
         else if (fileName.endsWith(".xml")) { 
          try { 
           IDSOutputGenerator.generateOutput(currFile.getAbsolutePath(), "", outputType, 
             false); 
          } catch (CheckErrorHandle e) { 
           throw new CheckErrorHandle(); 
          } 

         } else { 
          throw new CheckErrorHandle(currFile.getAbsolutePath(), "File type not supported"); 
         } 
        } 
       } catch (CheckErrorHandle e) { 
        throw new CheckErrorHandle(); 
       } catch (Exception e) { 
        throw new CheckErrorHandle("", e.getMessage()); 
       } 
      } else { 
       throw new CheckErrorHandle(currFile.getAbsolutePath(), "File does not exist"); 
      } 
     } 
    } 
+3

如果抛出异常,则跳出循环。它还应该做什么?你可以做什么,是创建一个异常列表,不要抛出任何东西,但将它们添加到列表中,并且在循环之后,抛出一个包含该列表的异常(如果它不是空的) - 但是为什么你想要做那? – Stultuske

回答

5

喜欢的东西:

Exception ex = null; 
for (;;) { 
    ex = new Exception(); 
} 
if (ex != null) throw ex; 

或者,作为注释提示:

List<Exception> errors = new ArrayList<>(); 
for (;;) { 
    errors.add(new Exception()); 
} 
if (!errors.isEmpty()) { 
    //Do something with errors 
} 

总体思路是,只有你可以做的事情 - 扔前店例外的地方它。如果抛出异常 - 那么只有避免中断循环才能立即捕获。

-1

一种可能性 - 移动所述环的整个主体到其处理例外,而无需重新投掷的另一种方法:

例如

for (int i = 0; i < j; i++) { 
    File currFile = arrayOfFile1[i]; 
    handlefile(currFile); 
} 

和方法:

private void handleFile(File file) { 
    //body of loop in here 
    //log exceptions, don't re-throw 
} 

另一种可能性是havethe上述方法返回布尔成功标志:

循环:

for (int i = 0; i < j; i++) { 
    File currFile = arrayOfFile1[i]; 
    if (handlefile(currFile)) { 
     //do something on success 
    } else { 
     //do something on failure 
    } 
} 

方法:

private boolean handleFile(File file) { 
    try { 
    //do stuff 
    return true; 
    } catch (Exception e) { //or more specific exceptions/multi-catch 
    //log exception 
    return false; 
    } 
} 
+0

是这个错误? – NickJ