Last active
December 19, 2018 14:41
-
-
Save earthboundkid/ff009b80f05d66a8536744716e9f9e8e to your computer and use it in GitHub Desktop.
How to chain exceptions in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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