我有下面的代码.
private static void readStreamWithjava8() {
Stream<String> lines = null;
try {
lines = Files.lines(Paths.get("b.txt"), StandardCharsets.UTF_8);
lines.forEachOrdered(line -> process(line));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (lines != null) {
lines.close();
}
}
}
private static void process(String line) throws MyException {
// Some process here throws the MyException
}
Run Code Online (Sandbox Code Playgroud)
这里我的process(String line)方法抛出已检查的异常,我从lambda中调用该方法.此时需要抛出MyExceptionfrom readStreamWithjava8()方法而不抛出RuntimeException.
我怎么能用java8做到这一点?
简短的回答是,你做不到.这是因为forEachOrdereda Consumer,并且Consumer.accept没有声明抛出任何异常.
解决方法是做类似的事情
List<MyException> caughtExceptions = new ArrayList<>();
lines.forEachOrdered(line -> {
try {
process(line);
} catch (MyException e) {
caughtExceptions.add(e);
}
});
if (caughtExceptions.size() > 0) {
throw caughtExceptions.get(0);
}
Run Code Online (Sandbox Code Playgroud)
但是,在这些情况下,我通常会在process方法中处理异常,或者使用for-loops以旧式方式处理异常.
| 归档时间: |
|
| 查看次数: |
1416 次 |
| 最近记录: |