Make an App that Won't Freeze

In our last example, the programmer (you) introduced the exception right in the script.  But in real life applications, the exception may be caused by a user entering incorrect or unexpected data during run time.  And, the user can't necessarily see the code, or understand Python's error types.

The next example program works much like the previous ones, but it lets the user change the value of d — the denominato r— by entering data in the terminal instead of modifying the script.   

  • Enter, save, and flash exceptions_user_division_calc.py.  
  • (You can save time by opening and modifying exceptions_division_calc.py from the previous activity.)
# exceptions_user_division_calc.py

from microbit import *

sleep(1000)

print("Division Calculations")

while True:
    text = input("Enter numerator n: ")
    n = float(text)

    text = input("Enter denominator d: ")
    d = float(text)

    q = n / d

    print("Quotient q: ")
    print("q = n / d")
    print("  = ", n, " / ", d)
    print("  = ", q)

    print("Try again!")
    print()
  • The first time through the loop, try entering values like 20 for the numerator and 5 for the denominator.
  • Verify that the correct answer is displayed.
  • The second time through, try entering zero for the denominator.
  • Verify that the application halts and then displays the ZeroDivisionError exception.

 

 

  • The application has halted, so you will have to restart it by pressing and releasing the micro:bit module’s reset button (next to its USB port) or re-flashing the script.
  • Try typing some text like “Hello” in either the numerator or denominator prompts.
  • Make a note of the error. It is no longer a TypeError; it's a ValueError.