Exception Handling Primer

What it’s about

Have you ever filled out a web form and it just froze?  Or, maybe you had an app that stopped working for no apparent reason.  In many cases, these problems are caused by unhandled exceptions.  You have probably also encountered one when your micro:bit suddenly stopped working, and the LED display slowly scrolled an error message with a description and line number.  

Unhandled exceptions can affect your cyber:bot.  Imagine you are in a contest typing navigation commands that a micro:bit transmits over radio to your cyber:bot.  Instead of typing a number for wheel speed, you accidentally type some letters.  Your cyber:bot script is only expecting numbers, so the letters you type cause an exception.  Then, your cyber:bot stops because it didn’t have exception handling statements.  Meanwhile, the other team’s cyber:bot passes yours and wins.  

Now, imagine that you added exception handling statements that make your script tell you if it receives something other than the numbers it expects, so you try again and enter the numbers correctly.  Your team’s cyber:bot keeps executing the script, and your team is still in the race!

This activity shows how to add exception handling statements to your scripts, to prevent your cyber:bot from being the one with a script that freezes during a navigation contest.

Before you start

You will need:

  • A micro:bit module (on or off a cyber:bot)
  • A USB A to MicroB cable
  • A computer with:
    • Access to python.microbit.org
      -- or --
    • Mu editor installed

Complete this tutorial first:


After you finish

You will understand how exceptions can occur and be able to write exception handling code that keeps the application running.

After this, you will also be ready to move on to the next tutorials.