Intermediate Python · Lesson 8 of 14
Exceptions in depth
Use else and finally, create your own exception classes, chain errors with raise from, and clean up safely with the with statement.
Errors and exceptions showed try and except. A try / except / else / finally statement has two more parts. else runs only if nothing went wrong, and finally runs always, error or not, which makes it the place for clean-up work.
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("Done with", a, "/", b)
divide(10, 4)
divide(5, 0)Result: 2.5 Done with 10 / 4 Cannot divide by zero Done with 5 / 0
Catching several kinds
List several exception types in brackets to handle them the same way, or write several except blocks to handle them differently. Python checks them from top to bottom and uses the first that matches.
def parse_price(text):
try:
return float(text)
except (ValueError, TypeError):
return None
print(parse_price("4.99"), parse_price("free"), parse_price(None))
stock = {"apples": 10, "pears": 0}
for item in ["apples", "pears", "plums"]:
try:
per_box = 100 / stock[item]
print(item, per_box)
except KeyError:
print(f"No stock record for {item}")
except ZeroDivisionError:
print(f"{item} stock is zero")4.99 None None apples 10.0 pears stock is zero No stock record for plums
Your own exception classes
A custom exception is a class that inherits from Exception (classes come in Classes and objects; for now, copy the pattern). It gives an error a clear name that callers can catch on its own, and it can carry extra data. You raise it with raise statement.
class InsufficientFunds(Exception):
def __init__(self, balance, amount):
super().__init__(f"Need {amount}, but only {balance} available")
self.shortfall = amount - balance
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFunds(balance, amount)
return balance - amount
print(withdraw(100, 30))
try:
withdraw(50, 80)
except InsufficientFunds as e:
print("Error:", e)
print("Short by", e.shortfall)70 Error: Need 80, but only 50 available Short by 30
raise ... from: keeping the cause
Sometimes you catch a low-level error and raise a clearer one. raise NewError(...) from e links the two, so the original cause is kept in __cause__ and shown in the traceback.
class ConfigError(Exception):
pass
def read_port(settings):
try:
return int(settings["port"])
except (KeyError, ValueError) as e:
raise ConfigError("The port setting is missing or not a number") from e
try:
read_port({"port": "eighty"})
except ConfigError as e:
print("Error:", e)
print("Caused by:", type(e.__cause__).__name__)Error: The port setting is missing or not a number Caused by: ValueError
except: or except Exception: also hides real bugs, such as a misspelt variable name.Context managers and with
The with statement statement runs set-up code, then your block, then clean-up code, even if the block fails. Files use it to close themselves. You can write your own with contextlib.contextmanager: the code before yield is the set-up and the code in finally is the clean-up. (The @ line is a decorator, explained in Decorators.)
from contextlib import contextmanager
@contextmanager
def section(title):
print(f"--- {title} ---")
try:
yield
finally:
print(f"--- end of {title} ---")
with section("Report"):
print("Sales: 120")
try:
with section("Broken"):
print(10 / 0)
except ZeroDivisionError:
print("The error still reached us, after the clean-up")--- Report --- Sales: 120 --- end of Report --- --- Broken --- --- end of Broken --- The error still reached us, after the clean-up
with open("note.txt", "w", encoding="utf-8") as f:
f.write("Buy milk\n")
print("Closed after the block:", f.closed)
with open("note.txt", encoding="utf-8") as f:
print(f.read().strip())Closed after the block: True Buy milk
✎ Exercise
Create an exception InvalidAge. Write check_age(age) that raises it with the message age must be between 0 and 130 when the age is outside that range, and returns the age otherwise. Loop over the values and print OK: <age> for a good age, or <value>: <error message> when InvalidAge is raised.
Hint: class InvalidAge(Exception): pass is enough for the class. Put the call inside try and catch InvalidAge as e.
# your code here
for value in [25, -3, 140, 70]:
pass
Expected output:
OK: 25 -3: age must be between 0 and 130 140: age must be between 0 and 130 OK: 70
Show a solution
class InvalidAge(Exception):
pass
def check_age(age):
if age < 0 or age > 130:
raise InvalidAge("age must be between 0 and 130")
return age
for value in [25, -3, 140, 70]:
try:
print("OK:", check_age(value))
except InvalidAge as e:
print(f"{value}: {e}")OK: 25 -3: age must be between 0 and 130 140: age must be between 0 and 130 OK: 70
Check yourself
1. When does the finally block run?
finally runs in every case, which is why it is used for clean-up.
2. When does the else block of a try statement run?
else runs only if the try block finished without an exception.
3. What does raise ConfigError(...) from e do?
The original error is kept in __cause__, so nobody loses the real reason.