7

I have the code below.

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
}

Here my process(String line) method throws the checked exception and I'm calling that method from within the lambda. At that point need to throw the MyException from readStreamWithjava8() method without throwing RuntimeException.

How can I do this with java8?

aioobe
  • 413,195
  • 112
  • 811
  • 826
user3496599
  • 1,207
  • 2
  • 12
  • 28

1 Answers1

5

The short answer is that you can't. This is because forEachOrdered takes a Consumer, and Consumer.accept is not declared to throw any exceptions.

The workaround is to do something like

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

However, in these cases I typically handle the exception inside the process method, or do it the old-school way with for-loops.

aioobe
  • 413,195
  • 112
  • 811
  • 826