Member-only story
Functional Programming With Java: Exception Handling
Better ways to deal with disruptive conditions in functional code

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.