Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throwing exception inside the java 8 stream foreach

I am using java 8 stream and I can not throw the exceptions inside the foreach of stream.

 stream.forEach(m -> {
        try {

            if (isInitial) {
                isInitial = false;
                String outputName = new SimpleDateFormat(Constants.HMDBConstants.HMDB_SDF_FILE_NAME).format(new Date());
                if (location.endsWith(Constants.LOCATION_SEPARATOR)) {
                    savedPath = location + outputName;
                } else {
                    savedPath = location + Constants.LOCATION_SEPARATOR + outputName;
                }
                File output = new File(savedPath);
                FileWriter fileWriter = null;
                fileWriter = new FileWriter(output);
                writer = new SDFWriter(fileWriter);
            }

            writer.write(m);

        } catch (IOException e) {
            throw new ChemIDException(e.getMessage(),e);
        }

    });

and this is my exception class

public class ChemIDException extends Exception {
public ChemIDException(String message, Exception e) {
    super(message, e);
}

}

I am using loggers to log the errors in upper level. So I want to throw the exception to top. Thanks

enter image description here

like image 330
Kaushali de Silva Avatar asked Oct 29 '22 15:10

Kaushali de Silva


1 Answers

Try extending RuntimeException instead. The method that is created to feed to the foreach does not have that type as throwable, so you need something that is runtime throwable.

WARNING: THIS IS PROBABLY NOT A VERY GOOD IDEA

But it will probably work.

like image 191
PaulProgrammer Avatar answered Jan 02 '23 19:01

PaulProgrammer