Legends ofPythos
Claim your name
Writing Real Programs

Raising your own exceptions

Lesson 9 of 16

Watch the lesson5:26 · with Sigrid
So far, you have learned to catch errors with try and except. But sometimes the error is not a surprise. It is something you know about in advance: an argument that cannot be right.

Instead of silently returning a bad value or crashing later, Python lets you stop execution immediately by raising your own exception. This tells every caller, "the input was invalid; I am giving up." The message you attach to the exception becomes part of the traceback.

raise with a clear message

def divide(a, b):
    if b == 0:
        raise ValueError("b must not be zero")
    return a / b

print(divide(10, 2))   # 5.0
# divide(10, 0) would raise the ValueError above.
A function that refuses to do impossible work
raise takes an exception object. The most common built-in types are ValueError, TypeError, and KeyError. Pick the one whose name best describes what went wrong, then pass a short human-readable string. That string is what shows up in tracebacks, so write it like you would explain to another developer.

Validating arguments

def set_temperature(celsius):
    if not isinstance(celsius, (int, float)):
        raise TypeError("need a number")
    if celsius < -273.15 or celsius > 1000:
        raise ValueError("out of range")
    return f"{celsius} C"

print(set_temperature(20))   # 20 C
# set_temperature('hot') raises TypeError
Two checks, two different exception types

Letting it travel up

def inner(x):
    if x < 0:
        raise ValueError("no negatives")
    return x * 2

def outer(x):
    # no try/except here: errors keep climbing
    return inner(x) + 1

print(outer(3))   # 7
# outer(-5): the traceback shows both functions
An error climbs up through every function until something catches it
You do not have to catch an exception at the level where it is raised. It bubbles up through inner, then outer, and so on, until a try/except catches it, or the program stops with a traceback. This keeps low-level functions simple: they validate their own inputs and let higher layers decide how (or whether) to recover.

Your turn

0 of 2 solved

Exercise 1

+35 XP
Write set_age(age) that returns 'OK' for a valid age. Raise TypeError with a message of your own, such as 'age must be a number', if age is not a number, and ValueError if it is below 0 or above 150. Check the type first.

isinstance(x, (int, float)) is True when x is a number: a whole number or a decimal.
def set_age(age):
    pass

Run your code to check it against the tests.

Exercise 2

+35 XP
Write two functions that work together:
  1. parse_score(raw) — takes a value and returns it as an int if possible. If raw is not convertible to int (for example 'abc', None, [1]), raise ValueError with the exact message 'bad score input'.
  2. submit_scores(scores) — takes a list of raw values, parses each one via parse_score, and returns the parsed ints as a new list in order. If ANY element is invalid, let that ValueError propagate up to the caller (do NOT catch it inside submit_scores).
Don't put one function inside the other.

except (KeyError, IndexError): catches either of the errors in the brackets. If you call parse_score(None) yourself, Python shows two tracebacks, the first error and then your ValueError: that is normal here.
def parse_score(raw):
    pass


def submit_scores(scores):
    pass

Run your code to check it against the tests.