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?

6
  • 3
    Note: you can use try-with-resources with Files.lines() Commented May 11, 2015 at 9:46
  • 1
    try(Stream<String> lines = Files.lines(Paths.get(...))) { ... } and remove the finally block. Commented May 11, 2015 at 9:53
  • 1
    @assylias Problem is my process() method throws the Checked Exception and how can I throw it from readStreamWithjava8() method. Commented May 11, 2015 at 10:04
  • 2
    @user3496599, try-with-resources is not about solving your problem. It's about writing shorter code. Commented May 11, 2015 at 10:17
  • 1
    See also here and here Commented May 11, 2015 at 11:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.