The division script we have been using includes statements that will fit into each part of a full exception-handling compound statement.
- Flash this script into the micro:bit:
# exceptions_division_calc_try_this.py from microbit import * sleep(1000) print("Division Calculation") try: n = 20 d = 5 q = n / d except Exception as e: print("Exception = ", e) et = type(e) print("Exception type = ", et) else: print("q = n / d") print(" = ", n, " / ", d) print(" = ", q) finally: print("Try again!") print()
- Verify that, as written, the script’s output works as expected without reporting errors:
Do you remember how to break the script?
- Modify the script by setting d equal to 0.
- Re-flash the script, and verify that it displays the division by zero exception text and its type:
Note that the script did not halt at the exception. Instead, it displayed the exception, but continued to print "Try again!"
Now let's break it with text one more time.
- Set d equal to "Hello" this time.
- Re-flash the script and verify that it displays the TypeError exception information:
Note again that the script did not halt at the statement that caused the exception. It made it all the way through printing "Try again!"