Java and Spring Level 3 This level · 8 of 56
Hard java streams

How are exceptions handled in Streams?

The 30 second answer

Unchecked exceptions from a lambda propagate out of the terminal operation and abort the pipeline. Checked exceptions cannot be declared on Function or Predicate, so I wrap them as unchecked, map failures into a result type, or leave the stream and use a loop when per-element error handling is the real logic. Close resource streams with try-with-resources.

Could you say this in an interview?
  • Unchecked exceptions thrown in a lambda propagate out of the terminal operation and abort the pipeline.
  • Checked exceptions cannot be thrown from Function, Predicate, and similar types because their functional methods declare no throws clause.
  • [Opinion] Options: wrap in a helper that catches and rethrows as unchecked (UncheckedIOException for IOException); map failures into a result type (for example Optional or an Either-style record) and filter later; or move the throwing code out of the stream into a loop when per-element error handling is the core logic.
  • In parallel streams an exception from one task is rethrown in the caller; other tasks may continue briefly. [Opinion / Impl — not specified in detail by the Javadoc]
  • Streams on I/O resources (Files.lines) must be closed: use try-with-resources; BaseStream is AutoCloseable.

Readability tip: [Opinion] Prefer streams for declarative transforms and aggregations; prefer loops for complex control flow, early exits with multiple states, checked exceptions, or hot paths where profiling shows overhead.

Sources (5)
  1. JLS §11 Exceptionsdocs.oracle.com
  2. Function.applydocs.oracle.com
  3. UncheckedIOExceptiondocs.oracle.com
  4. BaseStream.closedocs.oracle.com
  5. Files.linesdocs.oracle.com
Previous
Next