如何捕获异常并继续Java中的处理

时间:2012-03-21 04:34:38

标签: java exception loops

我有一个应用程序,我在循环中处理5000个文件到6000个文件。

在try和catch块中,我正在读取excel文件并处理每个单独的单元格。

当然所有文件都采用相同的格式,但在某些文件中,单元格中的数据可能会有所不同,但可能包含数据

处理第100个文件时出现异常, 停止整个处理并抛出异常,

但我不想要这种情况,相反,如果在第100个文件中存在异常,则迭代应继续使用第101个文件。 最后,我应该知道哪个文件是成功处理的,哪个文件是失败的。

我得到的例外是 NumberFormatExceptionNullPointerExceptions

如何处理这种情况?

3 个答案:

答案 0 :(得分:8)

基本思想是将try-catch块放在循环中。

for (File file : files) {
    try {
        parseExcelFile(file); // Do whatever you want to do with the file
    }
    catch (Exception e) {
        logger.warn("Error occurs while parsing file : " + file, e);
    }
}

答案 1 :(得分:5)

我这样做的方法是使用文件名作为键创建一个Map,并在循环中为每个异常创建一个可以在文件名下存储异常。您知道捕获的异常以及与之关联的文件。

Map fileExceptions = new HashMap<String, Exception>();

for(File file : files){
   try{
        <file processing>
   }
   catch(NumberFormatException e){
       fileExceptions.put(fileName, e);
   }
   catch(NullPointerException e){
       fileExceptions.put(fileName, e);
   }
}

答案 2 :(得分:4)

如果没有看到某些代码,很难更具体,但这可能是一种可能的方法:

public void processFiles(List<File> fileList)
{
    for (File thisFile : fileList) {
        try {
            processOneFile(thisFile);
        }
        catch (Exception ex) {
            printLogMessage(thisFile.getName());
        }
    }
}