在 java 8 流 foreach 中抛出异常

Kau*_*lva 7 error-handling java-8 java-stream

我正在使用 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);
        }

    });
Run Code Online (Sandbox Code Playgroud)

这是我的异常类

public class ChemIDException extends Exception {
public ChemIDException(String message, Exception e) {
    super(message, e);
}
Run Code Online (Sandbox Code Playgroud)

}

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

在此输入图像描述

Pau*_*mer 2

尝试延长RuntimeException。创建来提供给 的方法foreach不具有可抛出类型,因此您需要运行时可抛出的类型。

警告:这可能不是一个好主意

但它可能会起作用。

  • 你或许应该解释为什么这是一个坏主意,而不是帮助他们继续搬起石头砸自己的脚,别无选择。 (2认同)