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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9798634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:45:32  来源:igfitidea点击:

how to catch exceptions and continue the processing in Java

javaexceptionloops

提问by gmhk

I have an applicaton where I am processing 5000 files to 6000 files during a loop.

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

In a try and catch block I am reading the excel file and processing each individual cell.

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

Of course all the Files are in the same format, but In some files the data in the cell in may vary it may contain data or not

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

when ever there is an exception while processing 100th file, the whole processing is stopped and exception is thrown,

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

But I dont want that scenario, instead if there is an exception at 100th file, the iteration should continue with 101th file. And in the end I should know which file is processed succesfully and which one is failed.

但我不希望出现这种情况,如果第 100 个文件出现异常,则迭代应继续第 101 个文件。最后我应该知道哪个文件处理成功,哪个文件处理失败。

Exception which I am gettng are NumberFormatExceptionand NullPointerExceptions

我得到的例外是 NumberFormatExceptionNullPointerExceptions

How to hand that scenario?

如何处理这种情况?

回答by jahroy

It's hard to be more specific without seeing some code, but this could be a possible approach:

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

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

回答by Rangi Lin

The basic idea is to put the try-catch block inside the loops.

基本思想是将 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);
    }
}

回答by DavidB

The way I would do it is to create a Map using the filename as a key and in your loop for each exception you could store the exception under the filename. You'd know which exceptions you caught and the files they were associated with.

我这样做的方法是使用文件名作为键创建一个 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);
   }
}