Java 8 foreach thread exception exception

I am using java 8 thread and I cannot throw exceptions inside foreach thread.

 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 use loggers to record errors at the top level. Therefore, I want to throw an exception. Thanks

enter image description here

+4
source share
2 answers

Try to expand RuntimeException. The method created to feed in foreachdoes not have the type throwable, so you need something that can be executed in runtime.

WARNING: THIS IS A PROBLEM IS NOT A VERY GOOD IDEA

But it will probably work.

+2
source

forEach, , , , , - ? , , forEach ( Stream API , forEach), isInitial.

:

Optional<String> o = stream.findFirst();
if(o.isPresent()) try {
    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(o.get());
} catch (IOException e) {
    throw new ChemIDException(e.getMessage(),e);
}

. , Streams String. Optional<String>.


, , isInitial , . " " " " API, " " , . forEach .

0

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


All Articles