Pro Programmer
Errors And Exceptions

Errors and Exceptions

A programmer’s expertise is largely about how to deal with errors. Expert programmers love errors because, for them, errors mean progress.

Sometimes we expect to see these wonderful red messages and if we do not we know that the code is simply wrong!

I love the phrase “listen to your code” because I think code evolves by communicating to us using errors.

This is exactly like raising kids.

The most important parenting concept that I realized, with practice, is how kids communicate by misbehaving. This is because they do not have a logical brain yet. I think programs do the exact same thing. They also communicate by misbehaving (producing errors) because programs are not completely logical. Your task as a programmer is to add more logic in the code to handle the cases that originally produced errors. This is just like how a parent’s task is to teach the misbehaving kid what is wrong with that bad behavior and what to do differently next time.

Some errors are not recoverable and a program encountering those should just exit (and be rebooted). This is like if your heart stops. There is not much that can be done except to reboot it with an electric shock. This is why we monitor our programs and reboot them when they get to that state. Luckily, the process of rebooting a program is not as dramatic.

Most errors that happen during the early development of programs help improve these programs so that the errors never happen again. This is how good kids are raised. They do not repeat the misbehaving because now they have good logic to guide them in a good direction.

Some errors evolve to be exceptions. Exceptions are expected errors, ones that we can plan for and recover from. The best coding example here is a Network Connection error while we make a program download some data. This is very much expected because we know network connections could be unreliable, so we plan for that error. When it happens, let’s label the task of downloading that data as incomplete, queue it somewhere, and re-try it at a later time (see below for an analogy for queuing).

What we did with this planned exception is give the computer a different set of instructions (a different recipe) to do when that error happens. We do exactly that with our kids as well. We give them instructions about what to do in certain future scenarios that we expect (or fear in this case).

// Hey kids
if (stranger.offersYou(chocolate)) {

if (stranger.triesToForceYouToDoSomething()) {