PythonMastery

Raise an exception in Python

Use raise to stop a function when its arguments are wrong. A BMI function raises ValueError with a clear message, and the caller catches it.

Your own functions can raise exceptions too. When a function gets an argument it cannot use, raise stops it at once and tells the caller what is wrong. This is better than returning a wrong answer without any warning.

The program

python
def bmi(weight_kg, height_m):
    if weight_kg <= 0:
        raise ValueError(f"weight_kg must be more than 0, got {weight_kg}")
    if not 0.5 <= height_m <= 2.5:
        raise ValueError(f"height_m must be in metres (0.5 to 2.5), got {height_m}")
    return weight_kg / height_m ** 2


print(f"BMI: {bmi(68, 1.75):.1f}")

for weight, height in [(68, 175), (-5, 1.75)]:
    try:
        print(f"BMI: {bmi(weight, height):.1f}")
    except ValueError as error:
        print("Error:", error)
output
BMI: 22.2
Error: height_m must be in metres (0.5 to 2.5), got 175
Error: weight_kg must be more than 0, got -5

How it works

If nobody catches the exception, the program stops with a traceback that ends with your message:

python
ValueError: height_m must be in metres (0.5 to 2.5), got 175

Which exception to raise

Use one of Python's built-in types when it fits:

python
def repeat(text, times):
    if not isinstance(times, int):
        raise TypeError(f"times must be an int, not {type(times).__name__}")
    return text * times


try:
    repeat("ab", "3")
except TypeError as error:
    print("Error:", error)
output
Error: times must be an int, not str

When none of these fits, make your own type. The custom exception program shows how.

Learn the idea: Exceptions: Patterns Beyond the Basics, Functions & Scoping