Try This: Add Exception Handler

The division script we have been using includes statements that will fit into each part of a full exception-handling compound statement.

Example script: exceptions_division_calc_try_this

  • Change project's name from  exceptions_division_calc to exceptions_division_calc_try_this.
  • Update it to match the script below
  • Save the modified script.
  • Click the Send to micro:bit button.
# exceptions_division_calc_try_this

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()
  • Check the results in the serial monitor.
  • 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 with d = 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 with d = "Hello".
  • 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!"