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
- Connect your micro:bit module to your computer with its USB cable.
- In a Google Chrome or Microsoft Edge browser, go to python.microbit.org to open the micro:bit Python Editor.
- Enter, name, and save exceptions_division_calc.
(See Save & Edit Scripts.) - Click Send to micro:bit.
(See Flash Scripts with Python Editor.)
# 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()
- If it's not already open, click Show serial to open the serial monitor.
(See Use the Serial Monitor.) - Verify that your serial monitor 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: