Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 06 / Topic 6 of 10

raise: create your own error

Use raise when your rule is broken, even if Python sees no problem.

Real-world example: an age field on a form.

def set_age(age):
    if age < 0 or age > 120:
        raise ValueError(f"Age must be 0-120, got {age}")
    return age

try:
    set_age(150)
except ValueError as e:
    print("Error:", e)      # Error: Age must be 0-120, got 150

Re-raise

Sometimes you want to do something (like log) and then let the error continue. Use a bare raise inside except.

def load_price(prices, item):
    try:
        return prices[item]
    except KeyError:
        print(f"LOG: missing price for {item}")
        raise                    # send the same error up to the caller

try:
    load_price({"tea": 15}, "cake")
except KeyError as e:
    print("Caller got:", repr(e))   # repr() shows the type and the message
LOG: missing price for cake
Caller got: KeyError('cake')

raise ... from (brief)

Turn a low-level error into a clearer one, and keep the original as the cause.

def read_pin(text):
    try:
        return int(text)
    except ValueError as e:
        raise ValueError("PIN must be 4 digits") from e

try:
    read_pin("12a4")
except ValueError as e:
    print(e)                 # PIN must be 4 digits
    print(repr(e.__cause__)) # ValueError("invalid literal for int() with base 10: '12a4'")

The original error is kept in e.__cause__.

๐Ÿ” Going deeper: if this error is not caught, the traceback shows both errors joined by "The above exception was the direct cause of the following exception". raise ... from None hides the original (see section 9). Since Python 3.11 you can also add extra detail with e.add_note("...").

Done here? The practice set for Part 6 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide