gmhk
gmhk

Reputation: 15940

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?

Upvotes: 9

Views: 42083

Answers (3)

Rangi Lin
Rangi Lin

Reputation: 9451

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);
    }
}

Upvotes: 11

DavidB
DavidB

Reputation: 2234

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);
   }
}

Upvotes: 6

jahroy
jahroy

Reputation: 22692

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());
        }
    }
}

Upvotes: 4

Related Questions