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
raise ValueError("...")creates an exception object with a message and raises it. The function stops on that line, and thereturnnever runs.- The second call passes the height in centimetres (175) by mistake. Without the check, the function would return about 0.002, a wrong result with no error.
- A good message says which argument is wrong, what was expected, and what value was received.
got {height_m}saves the caller from guessing. - The function only raises. The caller decides what to do: here it catches the error with
except ValueError as errorand prints the message.
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:
ValueError: the type is right but the value is not allowed (a negative weight, an empty name).TypeError: the argument is the wrong type (a string where a number is needed).KeyErrororIndexError: something you looked up does not exist.
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.