Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch exceptions and continue the processing in Java

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

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

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,

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.

Exception which I am gettng are NumberFormatException and NullPointerExceptions

How to hand that scenario?

like image 942
gmhk Avatar asked Mar 21 '12 04:03

gmhk


3 Answers

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

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);
    }
}
like image 137
Rangi Lin Avatar answered Nov 11 '22 01:11

Rangi Lin


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 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);
   }
}
like image 26
DavidB Avatar answered Nov 11 '22 01:11

DavidB


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());
        }
    }
}
like image 4
jahroy Avatar answered Nov 11 '22 02:11

jahroy