Error handling
raise ValueError("message") stops the function right there and hands the
caller a specific, named problem instead of a wrong answer or a crash further
down the line. It's how you say "this input is bad, and here's exactly why" -
far more useful to whoever calls your function than a silent None or a
confusing error somewhere else.
try / except is how the caller decides what to do about it. Code inside
try runs normally until something raises; except ValueError: catches
that specific exception type and runs its block instead of letting the
program crash. Catching the exact exception type matters - an unrelated bug
shouldn't get silently swallowed along with the one you meant to handle.
Your task: write divide(a, b), which raises ValueError("cannot divide by zero") when b is 0, and otherwise returns a / b. Then write
safe_divide(a, b), which calls divide(a, b) but catches that ValueError
and returns None instead of letting it propagate.
You'll practice:
Raising a specific exception with raise
Catching it with try / except and building one function on another
Show a hint
Show solution
Related reading: Errors & I/O - Exceptions and Files →
Previous Next