Exception Handling in Java Streams

Arindam Roy
The Startup
Published in
5 min readJul 5, 2019

--

Photo by Maximilian Weisbecker on Unsplash

Over the course of my time working with companies migrating from Java 7 to Java 8, I saw many people being excited using cool new features like streams and higher-order functions. Java 8 does away with a lot of boilerplate code and makes the code a lot less verbose.

But not doing exception handling properly can eventually end up with us having bloated lambdas which defeat the purpose of having clean code.

Here, I’d like to discuss a few of the things I’ve learned over time in handling exceptions within lambdas. Keep in mind, there are always multiple approaches to things like this, so take this with a pinch of salt. If you think there are better ways to do the things below, please do let me know.

Unchecked Exceptions

Let’s take an example use of streams: You are given a list of strings and you want to convert them all to integers. To achieve that, we can do something simple like this:

List<String> integers = Arrays.asList("44", "373", "145");
integers.forEach(str -> System.out.println(Integer.parseInt(str)));

The above snippet will work perfectly, but what happens if we modify the input to contain an illegal string, say "xyz". The method parseInt() will throw a NumberFormatException , which is a type of unchecked exception.

--

--

Arindam Roy
The Startup

Product @hyperverge. I write about a lot of things, mostly tech.