Raising exceptions

Topic 2 of 4 in Errors and files6 min readBeginnerFree course

Overview

In the last lesson you caught exceptions raised by Python. Your own functions can raise them too. When a function receives something it can’t work with, raising an exception is the clearest way to say “I can’t do this — and here’s why”, and to let the caller decide what to do.

raise

Python
def set_age(age):
    if age < 0:
        raise ValueError("age can't be negative")
    return age

set_age(-3)
Text
Traceback (most recent call last):
  File "people.py", line 6, in <module>
    set_age(-3)
    ~~~~~~~^^^^
  File "people.py", line 3, in set_age
    raise ValueError("age can't be negative")
ValueError: age can't be negative

raise immediately stops the function — like return, but signalling failure. The exception travels back up through the calls until some try/except catches it, or the program stops. The traceback lists every call along the way, most recent last.

Why raise instead of print or return?

Consider the alternatives:

Python
def withdraw(balance, amount):
    if amount > balance:
        print("Not enough money!")    # the caller can't react to this
        return balance                 # and carries on as if it worked
Python
def withdraw(balance, amount):
    if amount > balance:
        return -1                      # is -1 an error or a real balance?

Printing hides the problem from the code that called you. Special return values like -1 or None are easy to forget to check — and then they flow silently into later calculations. An exception can’t be ignored by accident: either the caller handles it, or the program stops and points straight at the problem.

Choosing an exception type

Use a built-in type when one fits — callers already know how to catch them:

Situation Raise
right type, unacceptable value (negative age, empty name) ValueError
wrong type entirely (a string where a number is needed) TypeError
a requested key or item doesn’t exist KeyError, IndexError, LookupError
a feature isn’t written yet NotImplementedError
an operation isn’t valid in the current state RuntimeError

Always include a message that explains what was wrong — ideally with the bad value: ValueError(f"invalid month: {month}").

Custom exceptions

For errors that are specific to your program, define your own exception class. It only takes two lines (classes are covered fully in Classes and objects):

Python
class InsufficientFundsError(Exception):
    """Raised when a withdrawal is larger than the balance."""

Inheriting from Exception makes it a proper exception. Now callers can catch exactly this problem:

Python
try:
    withdraw(50, 80)
except InsufficientFundsError as error:
    print("Sorry:", error)

In bigger programs, it’s common to create one base exception and several specific ones under it, so callers can catch either a particular problem or all of them:

Python
class ShopError(Exception): ...
class OutOfStockError(ShopError): ...
class PaymentDeclinedError(ShopError): ...

Re-raising and adding context

Sometimes you want to do something when an error happens — log it, clean up — and then let it continue upwards. A bare raise inside except re-raises the same exception:

Python
try:
    process(order)
except PaymentDeclinedError:
    log("payment failed for order", order)
    raise

To turn a low-level error into a more meaningful one, use raise … from …; the traceback then shows both:

Python
try:
    port = int(settings["port"])
except (KeyError, ValueError) as error:
    raise RuntimeError("the settings file has no valid port") from error

assert: checking your own assumptions

assert checks a condition and raises AssertionError if it’s false:

Python
def average(numbers):
    assert len(numbers) > 0, "average() needs at least one number"
    return sum(numbers) / len(numbers)

Asserts are for catching programming mistakes — conditions that should never be false if your code is correct. They can be switched off (running Python with -O skips them), so never use them to validate user input or data from files; use if … raise for that. You’ll use assert constantly in tests (Testing with pytest).

Where to handle errors

A good pattern:

  • Low-level functions raise — they know what went wrong but not what the program should do about it.
  • The top level catches — the code that talks to the user decides how to respond: show a message, ask again, skip the record.
Python
def parse_quantity(text):
    qty = int(text)                       # may raise ValueError
    if qty <= 0:
        raise ValueError("quantity must be positive")
    return qty

# in the user-facing part of the program
try:
    qty = parse_quantity(input("How many? "))
except ValueError as error:
    print("Invalid quantity:", error)

Remember: functions raise, callers decide. Pick a fitting exception type, write a helpful message, and save assert for checks that should never fail.

Exercise

A bank account with rules

Write InsufficientFundsError, a custom exception that inherits from Exception. Then write withdraw(balance, amount) that returns the new balance, but raises TypeError if amount isn’t an int or float, ValueError if amount is zero or negative, and InsufficientFundsError (with a message saying how much is missing) if the amount exceeds the balance. Call it with the five test cases in the starter, catching each error and printing <ErrorType>: <message>.

Python
# 1. Custom exception

# 2. withdraw(balance, amount)

# 3. Try each case
cases = [(100, 30), (100, "30"), (100, -5), (100, 150), (50, 50)]

Summary

  • raise ValueError("message") stops the function and passes the problem to the caller.
  • Raise errors for invalid input instead of returning special values or printing messages.
  • Use built-in types where they fit: ValueError for bad values, TypeError for wrong types, KeyError/LookupError for missing items.
  • Create custom exceptions with class MyError(Exception): pass for errors specific to your program.
  • assert condition, "message" checks assumptions during development — never use it to validate user input.