Exception Handling (Babysitter Edition)
Expert Advice from Tech Elevator Instructor, Ben Langhinrichs
Read along with Tech Elevator Instructor, Ben Langhinrichs, as he discusses Exception Handling and the role it plays in Software Development.
Editor’s Note: This article was originally published to Tech Elevator Instructor Ben Langhinrichs’ Linkedin. You can visit the original post here.
Time for another fun article on programming concepts, this time on exception handling. Or, as I like to say, “When you least expect it, expect it.”
Exception handling is all about writing code that should go a certain way, but deep down you are quite sure it won’t, because of Mondays and bosses and unplanned hiccups. Which of course makes me think of babysitting.
Hiring a babysitter is all about planning a desperately needed break from your beloved hellions, yet all too often, the best laid plans go all too wrong. This is true of any babysitter, mind you, whether it is your Mom or your neighbor or an eager high schooler. But it is never more true than when you get Helpless Hattie.
Helpless Hattie is the babysitter you get when your mom is on a cruise, your neighbor is in rehab, and it is Prom night at the local high school. Not your first choice, but she has a pulse and nothing else to do, so you’re willing to give her a try. After all, little Max and Pax are pretty easy kids. If they are cranky or hungry or sleepy or bored, all you have to do is feed them cereal with milk, and they will settle down.
Since the Finnegan twins are always hungry, this works out well. Except when it doesn’t. When the unexpected is expected, we try to do the expected, but we can catch exceptional situations and deal with them.
Which works out if the house is on fire, but not if you’ve run out of milk. Don’t raise exceptions when you should just check the values like a good programmer.
But even then, there are times to call 911 and times to ask a neighbor. Check values you can, then catch specific exceptions, then catch general exceptions last.
Much better, but I just realized that the babysitter will never go home if an exception happens, and nobody wants that. So, we must make sure that no matter what disasters occur, Helpless Hattie will finally go home.
So, when you expect the unexpected in your own code, think of Helpless Hattie. First, try to do what you need to do, remember to catch any unexpected exceptions with the more specific ones first and more general after, and when appropriate, make sure the babysitter finally goes home.
If you found this article interesting, and you think a career in coding could be for you, take the Tech Elevator Aptitude Test to see if it could be a fit! Happy Coding!