我正在使用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);
}
}
我使用记录器登录上级的错误。所以我想抛出异常顶部。由于
+1
从代码我可以看到,它看起来像你应该使用'for'循环而不是流。您试图在功能性环境中放置命令式代码。 –
+0
我想读取大文件并将一些元素写入另一个文件。这里我正在做的是用过滤器读取文件。所以我认为最好的方法是使用流 –