</>
Topic 9 of 10
Theory

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

Safe division

Easy+10 XP

Return a / b. If b is zero, don't crash — return None.

safe_div(6, 3) → 2.0
safe_div(1, 0) → None
main.pyLoading Python…
Output
Press "Check" to run the tests