Errors and exceptions
When something goes wrong, Python raises an exception. You can catch it:
try:
n = int("forty")
except ValueError:
n = 0
Common exceptions: ValueError (bad value), ZeroDivisionError (division by zero), KeyError (missing key), IndexError (missing index).
Raise your own exception with raise:
def set_speed(v):
if v < 0:
raise ValueError("Speed cannot be negative")
return v