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.

A Working Script to Break

  • Make sure your pythyon.microbit.org browser or Mu is connected to your micro:bit.
  • Enter, save, and flash this script:
# exceptions_division_calc.py

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()
  • Verify that your terminal response is consistent with your input. It should look something like this:

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: