Home > other >  How to break from forEach loop when exception occur
How to break from forEach loop when exception occur

Time:12-07

I have a forEach loop inside a for loop. Something like this.

for (Iterator iterator = notLoadedFiles.iterator(); iterator.hasNext();) {
            SwapReport swapReport = (SwapReport) iterator.next();
            Reader reader = Files.newBufferedReader(Paths.get(swapReport.getFilePath()));
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT);
            List<CSVRecord> initList = csvParser.getRecords();
            
            CSVRecord csvRecord = initList.stream().filter(record -> record.get(0).endsWith("@xxx.com")).findAny().orElse(null);
            if (csvRecord != null) {
                // partition the list
                List<List<CSVRecord>> output = ListUtils.partition(initList, chunkSize);

                // Set data by slice
                output.stream().forEach(slice -> {
                    String inParams = slice.stream().filter(record -> !record.get(0).endsWith("@xxx.com")).map(record -> "'"   record.get(0)   "'").collect(Collectors.joining(",")).toString();
                    try {
                          // Retrieve data for one slice
                          setAccountData(inParams);
                        }
                    } catch (SQLException e) {  
                        // How to break ?
                    }
                });
            }
        }

The forEach loop will execute the setAccount method. The try catch block inside the forEach loop is because setAccount throwing SQLException.

What I want to do is to stop(break) from the forEach loop in case there is an exception.

If there is an exception the inner loop will stop and for loop (outer loop) will proceed to the next element in the iterator.

How can I do that ?

Thank you

CodePudding user response:

Sadly, function .ForEach() did not provided a good way to break the loop. Although adding a return statement inside this loop could let the .ForEach() to continue next loop, but I'm sure that's not what you are asking.

Solution

Therefore, you can try to use a feature call .takeWhile() introduced in Java 9. For example, the code will be:

boolean varNameYouPrefer = true;
output.stream().takeWhile(slice -> varNameYouPrefer).forEach(slice -> {
    String inParams = slice.stream().filter(record -> !record.get(0).endsWith("@xxx.com")).map(record -> "'"   record.get(0)   "'").collect(Collectors.joining(",")).toString();
    try {
            // Retrieve data for one slice
            setAccountData(inParams);
        }
    } catch (SQLException e) {  
        // To break, set varNameYouPrefer to false.
        varNameYouPrefer = false;
    }
});

References

  • Related