Your Turn: Exception Handling

As mentioned in the previous Did You Know section, sometimes a catchall exception handler is okay for prototyping. 

Here is an example where a typing error is likely when entering numbers.  All the exception handler needs to do is tell you there was a mistake and then allow the while(True) loop to repeat.

  • Save terminal_controlled_bot_tethered_try_this as terminal_controlled_bot_tethered _your_turn.  
  • Flash the script into the micro:bit.

Example script: terminal_controlled_bot_tethered_your_turn

# terminal_controlled_bot_tethered_your_turn

from cyberbot import *

sleep(1000)

print("\nSpeeds are -100 to 100\n")

while(True):
    try:
        vL = int(input("Enter left speed: "))
        vR = int(input("Enter right speed: "))
        ms = int(input("Enter ms to run: "))
    
        bot(18).servo_speed(vL)
        bot(19).servo_speed(-vR)
        sleep(ms)
        bot(18).servo_speed(None)
        bot(19).servo_speed(None)

        print()  

    except:
        print("Error in value entered.")
        print("Please try again. \n")

 

  • Open the serial mnitor and click inside it..
  • Try typing some valid number values, then type something invalid, like abc.
  • Verify that it responds such that the exception does not stop the app, and that it simply displays a message to try again.