gmh*_*mhk 7 java loops exception
我有一个应用程序,我在循环期间处理5000个文件到6000个文件.
在try和catch块中,我正在读取excel文件并处理每个单独的单元格.
当然所有文件都采用相同的格式,但在某些文件中,单元格中的数据可能会有所不同,但可能包含数据
当处理第100个文件时出现异常时,整个处理停止并抛出异常,
但我不想要这种情况,相反,如果在第100个文件中有异常,则迭代应继续使用第101个文件.最后,我应该知道哪个文件是成功处理的,哪个文件是失败的.
我得到的例外是
NumberFormatException和NullPointerExceptions
如何处理这种情况?
基本思想是将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);
}
}
Run Code Online (Sandbox Code Playgroud)
我这样做的方法是使用文件名作为键创建一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果没有看到一些代码,很难更具体,但这可能是一种可能的方法:
public void processFiles(List<File> fileList)
{
for (File thisFile : fileList) {
try {
processOneFile(thisFile);
}
catch (Exception ex) {
printLogMessage(thisFile.getName());
}
}
}
Run Code Online (Sandbox Code Playgroud)