Skip to content

Instantly share code, notes, and snippets.

@earthboundkid
Last active December 19, 2018 14:41
Show Gist options
  • Save earthboundkid/ff009b80f05d66a8536744716e9f9e8e to your computer and use it in GitHub Desktop.
Save earthboundkid/ff009b80f05d66a8536744716e9f9e8e to your computer and use it in GitHub Desktop.
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