Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.
Here’s a little example of how exceptions work with Scala Futures, specifically looking at the
onComplete ‘Failure’ case.
In this example I start three Futures that run for different lengths of time, and the shortest-running
Future throws an exception:
Working with yoga is often interesting. You stretch and twist and focus, trying to be very conscious of your movements, and then one day in the middle of a twisting pose you see your left foot coming out from behind your right ear. At first that’s a real surprise, a shock. You think, “Well, that can’t be my foot over there,” and then you realize it is your foot, and with that comes a strong sense of accomplishment, and maybe a little smile.
Then you do the same pose in the opposition direction, but twist and stretch as you might, your right foot doesn’t come out from behind your left ear. You know you can’t push it any more, at least not while doing the pose properly, so you realize there’s a bit of an imbalance. You accept that there’s still more work to do, but it’s a good thing, so you push on.
I think life is like that too, or can be like that. If you enjoy the struggle, if it’s a worthy struggle — a path with heart — the effort comes willingly, and with its own rewards.
This is a page from my book, “A Survival Guide for New Consultants”
After I sold Mission Data in 2007, I also sold most of my belongings and drove to Alaska, a state I fell in love with during several vacations many years ago. As a result of that moving process, I sold over 400 books, keeping only the 100 or so “best” books that would fit in my car.
Forced to think about keeping only ~100 books, I learned that my favorite business books are:
Nice slogan. :)
“Always bear in mind that your own resolution to succeed is more important than any other thing.”
~ Abraham Lincoln (born in Hardin County, Kentucky)
Table of Contents
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.6, “Scala best practice: How to use the Option/Some/None pattern.”Back to top
For a variety of reasons, including removing
null values from your Scala code, you want to use what I call the Option/Some/None pattern. Or, if you’re interested in a problem (exception) that occurred while processing code, you may want to return Try/Success/Failure from a method instead of Option/Some/None.
“How do we convince people that in programming, simplicity and clarity — in short, what mathematicians call “elegance” — are not a dispensable luxury, but a crucial matter that decides between success and failure?”