You Already Know How to Code: Part 5

In Part 4, I showed you how you already know about loops. Here’s even more you already know about coding.

You Already Know About Error Handling

“What are you taking, I mean talking, about?”

Things in life don’t always go to plan. You know what I mean. You get to the train station only to find that all the trains are cancelled. It’s a disaster, how will you get to that important job interview on time? Your mind races, trying to think of how to resolve this situation. Could you call for a lift? Could you afford a taxi? Could you call and reschedule the interview? If you ever been in a situation like this, you’ve enacted error handling. Error handling in code is a lot like dealing with when things don’t go to plan. Ideally, the code will run smoothly with no problems. But sometimes, things go wrong. And it is for those occasions that error handlers are needed, to find an alternative path for the code to go in. It may not be able to achieve the original objective (just like you may not be able to get to your job interview), but it should be able to handle the situation gracefully (like a rescheduling phone call).

If we return to the skipping example used in Part 4, how could error handling be used here? Well, lots of things could go wrong when skipping. An example is that we could trip over the rope and fall over. If this happened in real life, we would probably want to inspect ourselves for an injury before continuing. And this is similar to what an error handler does in code. It will inspect the ‘error’ to see if it is a bad one. A bad error means that the code should stop executing. Some errors though, are not severe. The code can resume, and retry what it was trying to do before. In the case of skipping, if we find we are injured, we stop skipping. If we find we are unharmed, we can continue skipping (a retry).

Here’s our list of actions for skipping if we introduce error handling:

  1. Swing the rope
  2. When rope is almost touching feet, try to jump
  3. If trip and fall, inspect for injury
  4. If no injury and not tired, go back to 1. Otherise, stop skipping

Notice that instead of ‘jump’, we now ‘try to jump’. This is similar to how we would write an error handler in code, using the ‘try’ keyword. The ‘try’ keyword starts a block in which we expect errors may occur. We handle them later on in a block demarked by ‘except’.

Let’s see how we would represent this in code:

tired = False
count = 0
while tired is False:
	swing_the_rope = True
	try:
	    jump()
	except TripException:
	    injured = am_injured()
	    if injured:
                print("injured, stopping")
		break
	count = count + 1
	print("skip")
	if count >= 10:
		tired = True
		print("tired, stopping")

We’re using the same skipping loop as in Part 4, but this time we’ve added a try-except block around a function called ‘jump’. This means that if a trip occurs while running ‘jump’, it is represented in code by a ‘TripException’ (an Exception is a type of class that is raised in the event of an error). If a ‘TripException’ is caught, we go to the except block and execute that. If it is not caught, the code doesn’t execute the except block at all. So, let’s say a ‘TripException’ is caught. We then call the function am_injured(), which we haven’t defined, but we can imagine it returns True if there is an injury and False otherwise. If we are injured, the code issues a break. This breaks the while loop (i.e. stops it), and we will stop skipping.

If we were to run this code, and on the fifth skip we tripped and injured ourselves, the output would be:

skip
skip
skip
skip
injured, stopping

If we were to run this code, and on the fifth skip we tripped but had no injury so got back up and continued skipping, the output would be:

skip
skip
skip
skip
skip
skip
skip
skip
skip
skip
tired, stopping

The error handling allowed us to pick up right where we left off and continue skipping until we got tired.

If we were to run this code, and we didn’t trip at all, the output would be:

skip
skip
skip
skip
skip
skip
skip
skip
skip
skip
tired, stopping

No error handling was needed, and we just continued skipping until we got tired.

Conclusion

Error handling is needed when things in code don’t go to plan, and this is something that happens more often than you’d think! Good code has error handling in place to gracefully redirect the code when things go awry. It’s actually one of the more important parts of programming, and you should always code with ‘what could go wrong here?’ in mind, adding error handlers for those cases and even for unexpected cases.

Are you convinced yet, that you already know how to code? Read on in You Already Know How to Code: Part 6, or if you want to learn more, I recommend trying the free courses at CodeCademy or SoloLearn. See you next time!