Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to chain exceptions in Python
# Thing that creates exceptions
def r(n):
raise Exception(f"error: {n}")
# Add exceptions to a list
errors = []
for n in range(10):
try:
r(n)
except Exception as e:
errors.append(e)
# Re-raise them as a chain
def handle(errors):
if errors:
head, *tail = errors
if tail:
try:
handle(tail)
except Exception as e:
raise head from e
else:
raise head
handle(errors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.