Last active
April 6, 2023 16:23
-
-
Save atheiman/8abd739cc1066a2181d6b7c9629d3840 to your computer and use it in GitHub Desktop.
Store up encountered python exceptions in a loop and then raise them all at the end
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
4 * 2 = 8 | |
3 * 2 = 6 | |
Error processing num b - ValueError("invalid literal for int() with base 10: 'b'") - Traceback (most recent call last): | |
File "/Users/aheiman/tmp/script.py", line 8, in <module> | |
print(f"{num} * 2 = {int(num) * 2}") | |
ValueError: invalid literal for int() with base 10: 'b' | |
5 * 2 = 10 | |
Error processing num f - ValueError("invalid literal for int() with base 10: 'f'") - Traceback (most recent call last): | |
File "/Users/aheiman/tmp/script.py", line 8, in <module> | |
print(f"{num} * 2 = {int(num) * 2}") | |
ValueError: invalid literal for int() with base 10: 'f' | |
6 * 2 = 12 | |
Traceback (most recent call last): | |
File "/Users/aheiman/tmp/script.py", line 14, in <module> | |
raise Exception("Errors encountered:", errors) | |
Exception: ('Errors encountered:', [ValueError("invalid literal for int() with base 10: 'b'"), ValueError("invalid literal for int() with base 10: 'f'")]) |
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
import traceback | |
# Capture errors and do not raise until finished processing all items | |
errors = [] | |
for num in [4, 3, "b", 5, "f", 6]: | |
try: | |
print(f"{num} * 2 = {int(num) * 2}") | |
except Exception as e: | |
print(f"Error processing num {num} - {repr(e)} - {traceback.format_exc()}") | |
errors.append(e) | |
if errors: | |
raise Exception("Errors encountered:", errors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment