Try This: Add Exception Handler for User Errors

The first step to preventing a user from causing an exception is to test as many user mistakes as you can think of.  Make sure to record each type of exception that occurred.  You will need that list later so that each exception type can be handled properly.  

To speed up the process, use the except Exception as e block, and print the exception’s text and type.  This will allow you to keep the app running as you test various user errors that cause exceptions.  Here is an example.

Example script: exceptions_user_division_calc_try_this

  • Save a copy of exceptions_user_division_calc as exceptions_user_division_calc_try_this.
  • Add try...except...else...finally statements as shown here.
  • Remember to add indentation to the code blocks that are nested in try:, except:, else:, and finally:.
  • Flash the code.
# exceptions_user_division_calc_try_this.py

from microbit import *

sleep(1000)

print("Division Calculations")

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

        q = n / d

    except Exception as e:
        print("Exception = ", e)
        et = type(e)
        print("Exception type = ", et)

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

    finally:
        print("Try again!")
        print()
  • Click Serial to open the terminal.
  • Repeat the user mistakes you tried earlier, and make notes of what happened when you entered 0 and then "Hello" for the denominator.  
  • Make notes of the error types that were reported for each "mistake."
  • Can you make any other “mistakes” that cause exceptions? If so, record the error types you encounter.