0

is it possible to "simplify" this code (particularly the for loop) using the latest java features (streams, etc) ? I've read examples such as these but it seems to make the code harder to read.

In other words, if a checked exception is thrown inside the execution of the loop, I want it to be propagated to the method running the loop.

public void function() throws IOException {
    List<String> lines = new BufferedReader(new InputStreamReader(System.in)).lines().collect(Collectors.toList());
    for (String line : lines) {
        System.out.println(compute(line));
    }
}

public int compute(String path) throws IOException {
    // perform some compute and may throw IOException
   return 0;
}
HagridV
  • 81
  • 1
  • 7

2 Answers2

0

Short answer: No.

Longer answer: Yes, but with caveats.

Java's functional interfaces and streams were meant to facilitate functional programming. Functional programming focusses on immutable data and pure functions (that is, functions which have no side effects and always return the same result on the same arguments). If your method throws an IOException, this is apparently not a pure function, because it apparently reads from an external source. You should think about whether a functional programming style suits your needs in this case.

But if you really want to use streams and Java's functional interfaces, you can do one of the following:

  • Wrap the checked exception in unchecked ones. (If you compute function is under your control, it could throw your own UncheckedIOException with the real IOException wrapped in it).
  • Write your own functional interfaces which declare checked exceptions (but then, you won't be able to use them in a Java stream).
  • Catch the exception within your lambda and handle it yourself. This is not very readable however, and it defeats one of the purposes of exceptions, namely that you can perform error handling outside of the method producing the error.

There are some third-party libraries which help you doing this.

Hoopje
  • 12,677
  • 8
  • 34
  • 50
0

Add lombok dependency and use SneakyThrows:

import lombok.SneakyThrows;

    public class Application {
  public static void main(String[] args) {
    Stream<Integer> of = Stream.of(1, 2, 3, 4, 5);
    of.forEach(i -> foo(i));
  }

  @SneakyThrows
  public static void foo(int i) {
    System.out.println("i: " + i);
    if (i == 3) {
      throw new Exception("Error");
    }
  }
}
Igor Dumchykov
  • 347
  • 1
  • 15