参见英文答案 >
Java 8: Lambda-Streams,Filter by Method with Exception13个
我有下面的代码.
我有下面的代码.
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 }
这里我的进程(String line)方法抛出已检查的异常,我从lambda中调用该方法.此时需要从readStreamWithjava8()方法抛出MyException而不抛出RuntimeException.
我怎么能用java8做到这一点?
解决方法
简短的回答是,你做不到.这是因为forEachOrdered接受了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); }
但是,在这些情况下,我通常会在process方法中处理异常,或者使用for-loops以旧式方式处理异常.