Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active April 6, 2023 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atheiman/8abd739cc1066a2181d6b7c9629d3840 to your computer and use it in GitHub Desktop.
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
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'")])
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