How to catch exceptions and continue processing in Java

I have an application in which I process 5,000 files up to 6,000 files during a cycle.

In the try and catch block, I read the excel file and process each individual cell.

Of course, all files are in the same format, but in some files the data in the cell can change, can contain data or not.

when an exception ever occurs when processing the 100th file, all processing stops and the exception is thrown,

But I do not want this scenario, instead, if there is an exception in the 100th file, the iteration should continue with the 101st file. And in the end, I have to know which file is being processed successfully and which is unsuccessful.

The exception I get is NumberFormatException and NullPointerExceptions

How to convey this scenario?

+6
source share
3 answers

The basic idea is to put a try-catch block inside 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); } } 
+7
source

How I can do this is to create a map using the file name as the key, and in your loop for each exception you can save the exception under the file name. You know what 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); } } 
+5
source

It is difficult to be more specific without seeing any code, but it may be possible:

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

Source: https://habr.com/ru/post/911257/


All Articles