Make a Script Handle Exceptions

In this activity, you will start with a working script and then modify it to cause an exception.  As usual, the script will halt when it reaches the statement that causes the exception.  You will then add statements to “handle” the exception and prevent the program from halting.  Finally, you will add statements that display more helpful messages.

Example script: exceptions_division_calc

  • Make sure your micro:bit is connected to Mu or to python.microbit.org. (This link is to version 2 to match the screencaptures here).
  • Enter, save, and flash the exceptions_division_calc script:
# exceptions_division_calc

from microbit import *

sleep(1000)

print("Division Calculation")

n = 20
d = 5

q = n / d

print("q = n / d")
print("  = ", n, " / ", d)
print("  = ", q)
print("Try again!")
print()
  • Open the serial terminal and verify that your terminal response is consistent with your input. It should look something like the image below. (Push the reset button on the underside of the micro:bit if you need the code to repeat to see the enteire message.)

Now let's break the script!

  • Modify the script to set d equal to zero, like this:
    d = 0
  • Flash the modified script, and verify that you now get an error report like this one:

 

Let's break it a different way!

  • Modify the script again so d is set equal to Hello, like this:
    d = "Hello!"
  • Re-flash the script again and verify that you now see a different error reported in the terminal: