Java 8, How to handle exceptions in a stream?

Raouf Makhlouf
Quick Code
Published in
3 min readApr 10, 2020

--

Moving to Java 8 adopt the new approach pretty easily, and the resulting code tends to be shorter and easier to follow unless you have to deal with exceptions in a stream.

Photo by Math on Unsplash

Let’s consider the case of John, who was a developer. He’s been told by his boss that the customer wants to migrate this code to Java 8 :

John is thinking: Ah, I get it now I can change the for-loop by a stream, and I catch the exception. So easy!

This works but makes the code harder to read and understand.
Ideally, you would like to keep each intermediate operation as a single line when writing pipeline code.

--

--

Raouf Makhlouf
Quick Code

😎 Curious and passionate Web developer. Software Engineer | Blogger | Football Player | Music Fan | Traveler Stories: https://medium.com/@makhlouf.raouf