错误处理 – 在java 8流foreach中抛出异常

我正在使用
java 8流,我不能在流的foreach中抛出异常.

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

    });

这是我的异常课程

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

}

我正在使用记录器来记录上层的错误.所以我想将异常抛到顶部.谢谢

《错误处理 – 在java 8流foreach中抛出异常》

最佳答案 尝试改为扩展RuntimeException.为foreach提供的方法不具有throwable类型,因此需要运行时可抛出的东西.

警告:这可能不是一个非常好的想法

但它可能会奏效.

点赞