14

Java 8 officially introduce java.io.UncheckedIOException to JDK class libraries for lambda with Stream API, because lambda expressions can't declare its throws-clause and lambda body can't throw checked exception such as IOException.

What's idiom/best practice with UncheckedIOException and Stream API? What conditions do I explicitly throw new UncheckedIOException object, and when should I catch UncheckedIOException exception?

3
  • Related: codereview.stackexchange.com/questions/44392/… Commented May 1, 2014 at 10:45
  • 2
    minor point - lambdas certainly can throw IOExceptions, but only if the interface method they are representing does so as well. Commented May 1, 2014 at 14:19
  • @aepurniet Thanks your point, I implicitly presumed functional interface that has no throws-clause, such as java.util.function.Consumer<T> for Stream#forEach()... Commented May 2, 2014 at 8:33

1 Answer 1

9

You would throw it in the same circumstances as the library methods (BufferedReader.lines and Files.lines) that currently do it: that is, when you are wrapping an I/O exception resulting from an operation subsequent to opening a file (file opening operations still throw IOException). As for catching it, that depends on your strategy for IO error recovery: in other words, do whatever you do to handle the wrapped IOException in non-stream code.

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

2 Comments

IMO, regardless of the strategy for IO error recovery, it seems reasonable to catch/unwrap UncheckedIOException ASAP and rethrow as checked exception(IOException) within Stream API caller method. What do you think of this point?
@yohjp yes, catch/unwrap the unchecked exception from the stream code, then rethrow as IOException if that is what your method would do anyway, or else handle the IOException if that is what your method would do. PS. Is the answer accepted?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.