Better Programming

Advice for programmers.

Follow publication

Functional Programming With Java: Exception Handling

Better ways to deal with disruptive conditions in functional code

Ben Weidig
Better Programming
Published in
7 min readJun 22, 2020

Photo by Randy Fath on Unsplash

In my previous articles about functional programming, I’ve shown how to incorporate a more functional style into our Java code. But I’ve omitted a crucial topic: how to deal with exceptions.

The article about Java exceptions didn’t talk about how to handle them in lambdas and streams because it deserved its own article.

1. Exceptions in Lambdas 
2. Dealing With Exceptions the Java Way
3. A More Functional Approach
4. Third-Party Libraries
5. Conclusion
6. Resources

Exceptions in Lambdas

“Exception handling is a mechanism used to handle disruptive, abnormal conditions to the control flow of our programs.”

Java exception handling evolved over time with additions like multi-catch or try-with-resources, but sadly there aren’t any considerations for lambdas (yet). We still have to oblige to the catch-or-specify requirement of checked exceptions:

So we need to rely on try-catch to make the compiler happy:

I think we can all agree that introducing try-catch directly into a lambda is an ugly way to deal with Java’s nonfunctional exception handling.

The throwing and handling of exceptions is the opposite of what we strive to achieve with a more functional coding style. It’s quite verbose and can lead to impurity by making a function no longer deterministic (same input generates the same output). But there are ways to deal with exceptions without losing (most) of the simplicity and clearness of functional programming.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Ben Weidig
Ben Weidig

Written by Ben Weidig

Software developer, entrepreneur, blogger. Mostly Java, sometimes Swift, Golang, Bash and all the other fun stuff.

Responses (4)

Write a response