After this lesson you will be able to make your own functions report problems clearly, and create exception types that describe the problems of your own program. So far Python raised every error for you. Now you take control.
Raising an exception
The raise statement creates an exception and stops the current function. Give it a type and a message.
def set_quantity(quantity):
if quantity < 0:
raise ValueError("quantity cannot be negative")
return quantity
print(set_quantity(5))5set_quantity(-2)ValueError: quantity cannot be negativeA function that raises is saying "I cannot do this with what you gave me". The caller then decides: handle it with try, or let the program stop.
try:
set_quantity(-2)
except ValueError as err:
print("Rejected:", err)Rejected: quantity cannot be negativeChoose the built-in type that matches the problem. ValueError suits a bad value, TypeError a wrong kind of argument, KeyError a missing key and FileNotFoundError a missing file. Write the message for a person who will read it later: say what was wrong and, if useful, what was received.
def apply_discount(price, percent):
if not 0 <= percent <= 100:
raise ValueError(f"percent must be between 0 and 100, got {percent}")
return price * (100 - percent) / 100
print(apply_discount(80, 25))60.0apply_discount(80, 150)ValueError: percent must be between 0 and 100, got 150Defining your own exception
Built-in types cover many cases, but sometimes the problem belongs to your program: an out-of-stock item, an overdue library book. A custom exception is just a class that inherits from Exception. (Classes are explained in the object-oriented section, so treat this as a pattern to copy for now.)
class OutOfStock(Exception):
pass
def sell(stock, item, amount):
if stock.get(item, 0) < amount:
raise OutOfStock(f"only {stock.get(item, 0)} of {item} left")
stock[item] -= amount
return stock[item]
stock = {"pens": 3}
print(sell(stock, "pens", 2))1sell(stock, "pens", 5)OutOfStock: only 1 of pens leftThe benefit is that callers can catch exactly this problem and nothing else:
try:
sell(stock, "pens", 5)
except OutOfStock as err:
print("Cannot sell:", err)Cannot sell: only 1 of pens leftA tidy habit is to make one base class for a whole program, then derive more specific ones from it. Callers can then catch either the narrow type or the whole family.
class LibraryError(Exception):
pass
class BookNotFound(LibraryError):
pass
class BookAlreadyBorrowed(LibraryError):
pass
def borrow(catalogue, title):
if title not in catalogue:
raise BookNotFound(title)
if catalogue[title]:
raise BookAlreadyBorrowed(title)
catalogue[title] = True
return "Enjoy " + title
catalogue = {"Dune": False, "Emma": True}
for title in ["Dune", "Emma", "Ulysses"]:
try:
print(borrow(catalogue, title))
except BookAlreadyBorrowed:
print(title, "is already out")
except LibraryError:
print(title, "is not in the library")Enjoy Dune
Emma is already out
Ulysses is not in the libraryBecause BookNotFound inherits from LibraryError, the last except catches it.
Re-raising and chaining
Sometimes you want to react to an error and still let it continue upwards, for example to log it. A bare raise inside an except block does that, with the original traceback intact.
def read_count(text):
try:
return int(text)
except ValueError:
print("Logging: bad count", repr(text))
raise
try:
read_count("many")
except ValueError as err:
print("Caller saw:", err)Logging: bad count 'many'
Caller saw: invalid literal for int() with base 10: 'many'You can also turn a low-level error into a clearer one, keeping the original as the cause with from:
class ConfigError(Exception):
pass
def read_port(text):
try:
return int(text)
except ValueError as err:
raise ConfigError("port must be a whole number") from err
try:
read_port("http")
except ConfigError as err:
print(err)
print("Caused by:", repr(err.__cause__))port must be a whole number
Caused by: ValueError("invalid literal for int() with base 10: 'http'")assert is for your own assumptions
assert condition, message raises an AssertionError when the condition is false. Use it to document things that must be true if your code is correct, mostly while developing. Do not use it to check user input: assertions can be switched off when Python runs with the -O option, and a check that disappears is not a check.
def average(numbers):
assert len(numbers) > 0, "average needs at least one number"
return sum(numbers) / len(numbers)
print(average([4, 6, 8]))6.0average([])AssertionError: average needs at least one numberCommon mistakes
- Raising the bare
Exceptionclass.raise Exception("bad")forces callers to catch everything. Use a specific built-in or a custom type. - A vague message.
raise ValueError("error")helps nobody. Say what was wrong and what you received. - Using exceptions for normal flow. If a case happens all the time, handle it with an
ifinstead of raising and catching. - Writing
raise errwhen you meanraise. In most cases a bareraisekeeps the original traceback and is the clearer choice. - Validating user input with
assert. Useifandraisefor input checks, because assertions can be disabled.
Exercise
Define an exception InvalidMark and a function grade(mark) that raises it when the mark is below 0 or above 100, otherwise returns "pass" for 40 or more and "fail" below 40. Call it with 72, 25 and 130, catching the error for the last one.
Show one possible answer
class InvalidMark(Exception):
pass
def grade(mark):
if mark < 0 or mark > 100:
raise InvalidMark(f"mark must be 0 to 100, got {mark}")
return "pass" if mark >= 40 else "fail"
for mark in [72, 25, 130]:
try:
print(mark, grade(mark))
except InvalidMark as err:
print("Invalid:", err)72 pass
25 fail
Invalid: mark must be 0 to 100, got 130Next: reading files puts error handling to work, because files are where things often go wrong. A video version of this topic is in the video course at /learn/python/.
Key points
- raise ExceptionType(message) stops the current function and signals a problem to whoever called it.
- Pick the built-in type that fits, such as ValueError for a bad value, and write a message that says what was wrong.
- A custom exception is a class that inherits from Exception. It lets callers catch your specific problem.
- A bare raise inside except re-raises the same error, and raise NewError from err chains a cause onto a new one.
- assert is for checking your own assumptions while developing, not for validating user input.